update sqlite columns based on other columns information - python-3.x

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()

Related

counting strings through columns

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()

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])

sqlite3.OperationalError: 1 values for 3 columns

I am trying to insert and extract data using a sqlite database, but I keep running into this error:
Traceback (most recent call last):
File "Database_Section\Dsite.py", line 14, in <module>
insert("Cup", 4, 5)
File "Database_Section\Dsite.py", line 10, in insert
cur.execute(cur.execute("INSERT INTO store(item, quantity, price) VALUES ('?,?,?')", ('item','quantity','price')))
sqlite3.OperationalError: 1 values for 3 columns`enter code here
And this is my code:
import sqlite3
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS store(item TEXT, quantity INTEGER, price REAL)')
conn.commit()
def insert(item,quantity,price):
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute(cur.execute("INSERT INTO store(item, quantity, price) VALUES ('?,?,?')", ('item','quantity','price')))
conn.commit()
conn.close()
impo
insert("Cup", 4, 5)
def view():
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
print(view())
"INSERT INTO store(item, quantity, price) VALUES ('?,?,?')"
This tries to insert the literal string '?,?,?' to the table, and fails because it's a single value and there are 3 columns (as the errors says).
You should remove the quotes surrounding the placeholders:
"INSERT INTO store(item, quantity, price) VALUES (?,?,?)"

adding key:value from dictionary to sqlite3 db and retrieving them back

I am saving sequences with different ids associated with them as two column in sqlite3 DB where sequence is a column and ids_string are another column. I have problem with retrieving from the database
The dictionary is created as uniqe_sequence = [list of ids]
the sequence is a string of roughly 7000 characters or less and the list of ids could be up to 1 million characters
import sys
from Bio import SeqIO
from Bio.Seq import Seq
import time
import sqlite3
conn = sqlite3.connect('Sausql_012419.db')
c = conn.cursor()
c.execute("create table Sau (sequence text, list_of_ids text)")
for record in sequences_dict_d:
c.execute("insert into Sau values (?,?)", (record,'._/'.join(sequences_dict_d[record])))
conn.commit()
c.execute("SELECT COUNT(*) FROM Saureus_panproteome")
sql_count = c.fetchall()
print("saved sql database of {} proteins in --- {:.3f} seconds ---".format(sql_count[0][0],time.time() - start_time))
c.close()
conn.close()
#retrieval exact sequence match
for record in SeqIO.parse(queryfile, _format):
conn = sqlite3.connect('Sausql_012419.db')
c = conn.cursor()
c.execute('select list_of_ids from Sau where sequence = str(record.seq)')
print(c.fetchall()) # or do something with the list_of_ids

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