counting strings through columns - python-3.x

I'm pretty new to python or programming at all so I'd like to get help on the following problem
My table is set up like this:
https://i.imgur.com/KFPq2DI.png
Now I try to count all '✓' and set the number to column Teilnahme.
teilnahmencounter(ctx):
i=0
# Connect
connection = sqlite3.connect("kekse.db")
# cursor
cursor = connection.cursor()
# Abfrage
sql = "SELECT * FROM kekse ORDER BY ID"
cursor.execute(sql)
connection.commit()
for dsatz in cursor:
i = 0
for x in range(2 , 19):
if str(dsatz[x]) == '✓':
i += 1
cursor.execute('UPDATE kekse SET Teilnahme='+str(i)+' WHERE ID=?', dsatz[0]
)
connection.commit()
#print(dsatz[1], i, "Teilnahmen")
connection.close()

Try and use cast in your update where its getting updated -
import sqlite3
# Connect
con = sqlite3.connect("dbname.db")
# cursor
cur = con.cursor()
for row in cur.execute("select * from testtab"):
print(row)
cur.execute("update testtab set id=21 where id = cast("+str(2)+" as int)")
con.commit()
con.close()

Related

SQL UPDATE statement error in python code

I am trying to write a python function that updates a postgres database. The table to be updated is given (department)
Below is the function I wrote:
def modify_dept_budget(deptName, newBudget):
connection = None
try:
connection = connector() # This is a function I wrote to connect so I can hide my credentials.
cursor1 = connection.cursor()
query1 = f"select dept_name from department"
cursor1.execute(query1)
results1 = cursor1.fetchall()
results1 = [result[0] for result in results1]
if deptName in results1:
idx = results1.index(deptName)
print(results1[idx])
cursor2 = connection.cursor()
query = f"UPDATE department SET budget = %s WHERE dept_name == {deptName}"
cursor2.execute(query, [newBudget])
cursor3 = connection.cursor()
cursor3.execute(f'SELECT * FROM department')
results2 = cursor3.fetchall()
headers = [item[0] for item in cursor3.description]
df = pd.DataFrame(data = results2, columns = headers)
print(df)
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if connection:
cursor1.close()
cursor2.close()
cursor3.close()
connection.close()
When I run modify_dept_budget('Music', 85000), I get the following error:
Music
column "music" does not exist
LINE 1: ...PDATE department SET budget = 85000 WHERE dept_name == Music
^
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-77-16e7278e3358> in <module>
----> 1 modify_dept_budget('Music', 85000)
<ipython-input-76-80361b6ddf35> in modify_dept_budget(deptName, newBudget)
26 cursor1.close()
27 cursor2.close()
---> 28 cursor3.close()
29 connection.close()
UnboundLocalError: local variable 'cursor3' referenced before assignment
Can anyone help me figure out what is going on?
You have two problems. First, SQL does not use the double == for the equality test. Just plain =. Second, that string literal needs to be quoted. Unless you need a table name or a field name, you won't be using f-strings with SQL. So, do:
query = "UPDATE department SET budget = %s WHERE dept_name = %s"
cursor2.execute(query, [newBudget, deptName])

Function to parse a dataframe into a SQL table

I am trying to create a function that will accept a dataframe and will parse that dataframe into a sql server table. I am stuck as to what needs go in the select statement below the insert query.
df- dataframe
desttable - destination table that needs to be parsed.
tablecols - An array of the table columns for the table
# Insert DataFrame to Table
def InsertintoDb(self, df, desttable, tablecols):
tablecolnames = ','.join(tablecols)
qmark = ['?' for s in tablecols]
allqmarks = ','.join(qmark)
#rowappendcolname = ','.join(['row.' + s for s in tablecols])
for index, row in df.iterrows():
cursor.execute(
'''INSERT INTO [Py_Test].[dbo].''' + desttable + ''' ( ''' + tablecolnames + ''')VALUES (''' + allqmarks + ''')''',
)
self.conn.commit()
Any help is much appreciated.
As suggested by the gentleman in the comment, I was able to do it using df.to_sql . Here is the working code -
class DbOps:
def __init__(self):
self.username = ''
self.password = ''
self.ipaddress = 'localhost'
# self.port = 5439
self.dbname = ''
# A long string that contains the necessary Postgres login information
self.engine = sqlalchemy.create_engine(
f"mssql+pyodbc://{self.username}:%s#{self.ipaddress}/{self.dbname}?driver=SQL+Server+Native+Client+11.0" % urlquote(f'
{self.password }'))
def InsertintoDb(self, df, desttable, tablecols):
df.to_sql(desttable, self.engine, index=False, if_exists='append')

mysql.connector.errors.InternalError: Unread result found

input:
import mysql.connector
conn = mysql.connector.connect(host="localhost",
port="3306",
user="root",
database="database_name")
cursor = conn.cursor()
cursor.execute("SELECT asin FROM table_name LIMIT 5")
for i in cursor:
cursor.execute(f"UPDATE table_name SET `barkod` = '123321' WHERE `table_name`.`asin` = '{i}'")
output:
mysql.connector.errors.InternalError: Unread result found

update sqlite columns based on other columns information

I am trying to use information from a sqlite db and update another columns with some conditions using Python 3.6
python 3.6 and sqlite
def open_days(signed_date,completed_date):
fmt = '%Y-%m-%d'
if completed_date == '':
if signed_date:
sdate = datetime.strptime(signed_date, fmt)
tdate = datetime.now()
delta = str((tdate - sdate).days)
return delta
else:
sdate = datetime.strptime(signed_date, fmt)
cdate = datetime.strptime(completed_date, fmt)
delta = str((cdate - sdate).days)
return delta
conn = sqlite3.connect('mydb.db')
cur = conn.cursor()
cur.execute("SELECT * FROM data_table")
for row in cur:
cur.execute("UPDATE data_table SET days_open=? WHERE numid=?", (open_days(row[1],row[2]),row[0]))
cur.fetchall()
cur.close()
conn.commit()
I am expecting the result to be:
numid,signed_date,completed_date, number_of_days
1234,2019-05-15,,16
2345,2019-04-29,,32
3456,2019-04-29,2019-05-13,14
4567,,,None
the value are not udpated with the correct value if the number of days is set manually
numid,signed_date,completed_date, number_of_days
1234,2019-05-15,,16
2345,2019-04-29,,16
3456,2019-04-29,2019-05-13,16
4567,,,16
Note that it can be that no signed date and no completed date is already register into the db as per example showing some blank space between coma.
if signed date and completed date are registered then the number of day is the difference between completed date and signed date
if only signed date is registered then number of day is the difference between today's date and signed date
if no signed date then number of day is None
I have found a way to update the rows:
conn = sqlite3.connect('mydb.db')
conn.create_function('open_days', 2 , open_days)
cur = conn.cursor()
for row in cur.execute('SELECT signed_date, completed_date, open_days(signed_date,completed_date) FROM data_table'):
cur.execute('UPDATE data_table SET days_open=(open_days(signed_date,completed_date))')
cur.close()
conn.commit()
change to as per Sam input:
conn = sqlite3.connect('mydb.db')
conn.create_function('open_days', 2 , open_days)
cur = conn.cursor()
cur.execute('UPDATE data_table SET days_open=(open_days(signed_date,completed_date))')
cur.close()
conn.commit()

Insert 2 date values into columns in sqlite db using python

New to using sqlite with python. I am trying to insert two date values into two date columns in sqlite db via Python.
import sqlite3
def create_connection(db_file):
# Create a database connection to a SQLite database
# Param: db_file as str. Return: connection objects or None
try:
conn = sqlite3.connect(db_file)
cur = conn.cursor()
return conn, cur
except Error as e:
print (e)
return None
my_conn, my_cur = create_connection(dpd_sqlite_db_dir)
def create_sqlite_table_if_nonexist(conn, table_name):
sql = 'create table if not exists '+table_name+' (data_download_date datetime, script_executed_date datetime)'
conn.execute(sql)
create_sqlite_table_if_nonexist(my_conn, 'df_timestamp_en')
def insert_timestamp(conn, timestamp):
# execute insert into db
sql = ''' INSERT INTO df_timestamp_en (data_download_date, script_executed_date) VALUES(?,?) '''
cur = conn.cursor()
cur.execute(sql, timestamp)
return cur
timestamp_info = ('2018-10-30', '2018-11-30')
insert_timestamp(my_conn, timestamp_info)
It runs and created the table with two date columns, but it doesn't insert the timestamp_info's values.

Resources