issue with deleting rows in python sqlite [duplicate] - python

This question already has an answer here:
Unfindable SQLite Syntax Error
(1 answer)
Closed 4 months ago.
import pandas as pd
import sqlite3 as sql
import os
sea_level_df = pd.read_csv(r"C:\Users\slaye\OneDrive\Desktop\SeaLevel.csv", skiprows=3)
display(sea_level_df)
conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db")
cur = conn.cursor()
s = sea_level_df.to_sql('v', conn)
cur.commit(s)
conn.close()
class database:
def __init__(self):
conn = sql.connect('z')
cur = conn.cursor()
def create_table():
conn = sql.connect('z')
cur = conn.cursor()
n = """CREATE TABLE IF NOT EXISTS k(
id INTEGER PRIMARY KEY,
year INTEGER NOT NULL
sea_level INTEGER NOT NULL)
;"""
cur.execute(n)
conn.commit()
print("table created")
conn.close()
def insert():
conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db")
cur = conn.cursor()
query = ("""INSERT INTO v VALUES (1223, 2022, -17.89, 0, 0, 0);""")
cur.execute(query)
conn.commit()
t = ("""SELECT * FROM v;""")
w = cur.execute(t).fetchall()
print(w)
conn.close()
def remove():
conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db")
cur = conn.cursor()
g = ("""DELETE FROM v
WHERE index = 1221;""")
cur.execute(g)
conn.commit()
b = ("""SELECT * FROM v;""")
q = cur.execute(b).fetchall()
print(q)
conn.close()
def search():
conn = sql.connect(r"C:\Users\slaye\OneDrive\Desktop\sqlite\db\z.db")
cur = conn.cursor()
x = ("""SELECT * FROM v WHERE index = 1221;""")
h = cur.execute(x).fetchall()
print(h)
conn.close()
def test():
conn = sql.connect('z')
cur = conn.cursor()
u = cur.execute("""SELECT * FROM z;""").fetchall()
print(u)
So I'm having trouble with the functions titled "remove" and "search". I get these errors respectively:
OperationalError Traceback (most recent call last)
Input In [76], in <cell line: 1>()
----> 1 database.remove()
Input In [75], in database.remove()
33 cur = conn.cursor()
34 g = ("""DELETE FROM v
35 WHERE index = 1221;""")
---> 36 cur.execute(g)
37 conn.commit()
38 b = ("""SELECT * FROM v;""")
OperationalError: near "index": syntax error
OperationalError Traceback (most recent call last)
Input In [77], in <cell line: 1>()
----> 1 database.search()
Input In [75], in database.search()
45 cur = conn.cursor()
46 x = ("""SELECT * FROM v WHERE index = 1221;""")
---> 47 h = cur.execute(x).fetchall()
48 print(h)
49 conn.close()
OperationalError: near "index": syntax error
and the data is basically a csv stored within a dataframe stored within an sqlite database. for the remove function I'm just trying to remove a row of data and for the search function, I'm just trying to pull up a specific index.

Since "index" is a reserved keyword as listed here, have you tried adding brackets [index] or rename this field if you can ? Maybe something like [v_id] would be a better choice in my opinion.

Related

F-string formatting in SQLite gives OperationalError: no such column: Using Jupiter Notebook in VSCode

There is a DrugName column in the database, but I am getting this error that says the column does not exist.
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def select_by_slot(conn, slot_name, slot_value):
"""
Query all rows in the tasks table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT * FROM finale WHERE {}='{}'".format(slot_name, slot_value))
rows = cur.fetchall()
if len(list(rows)) < 1:
print("There are no resources matching your query.")
else:
print(rows)
# for row in random.sample(rows, 1):
# print(f"Try the {(row[0])}")
select_by_slot(create_connection("ubats.db"),
slot_name = 'DrugName',slot_value= 'Beclomethasone dipropionate 100mcg and formoterol fumarate dihydrate 6mcg pressurized inhalation solution')
I want to be able to search if a particular drug is in the column. If so, print the row. I have tried searching and using f-string formatting too, but it did not work.
Ideas please?
error message:
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/Users/karan/udev/ubat_db/talk_db.ipynb Cell 2 in <cell line: 33>()
29 print(rows)
30 # for row in random.sample(rows, 1):
31 # print(f"Try the {(row[0])}")
---> 33 select_by_slot(create_connection("ubats.db"),
34 slot_name = 'DrugName',slot_value= 'Beclomethasone dipropionate 100mcg and formoterol fumarate dihydrate 6mcg pressurized inhalation solution')
/Users/karan/udev/ubat_db/talk_db.ipynb Cell 2 in select_by_slot(conn, slot_name, slot_value)
16 """
17 Query all rows in the tasks table
18 :param conn: the Connection object
19 :return:
20 """
21 cur = conn.cursor()
---> 22 cur.execute("SELECT * FROM finale WHERE {}='{}'".format(slot_name, slot_value))
24 rows = cur.fetchall()
26 if len(list(rows)) < 1:
OperationalError: no such column: DrugName
the problem was apparently due to improper database creation.
df = pd.read_csv('/Users/karan/Downloads/ubat.csv')
df.to_sql('finale', conn, if_exists='append', index=False)
This way of creating the database solved the issue. Thanks all.

how do i access one record from query results in python

hi i have this query and its result i was trying to access record by record at a time but im not able to
select_migration_db = "SELECT B.rmt_n, A.prr_id, A.rp_ID FROM mo_TRAC A, T_sft_init_prr B WHERE A.rp_id=B.int_prr_id AND A.STATUS='Sc' AND A.PHASE='first' AND A.WAVE='first'"
def my_query(query,cursor):
conn = oracle.connect(user=user,password=pwd,dsn = host,encoding="UTF-8")
cursor = conn.cursor()
return cursor.fetchall()
rows =my_query
for r in rows:
print (r)
the table result looks like
rmt_n prr_id rp_ID
ss_tt_1 1456 767
rr_mm_2 663 889
ss_op_3 8894 999
You have lots of really basic errors:
You're not calling the function with my_query(select_migration_db).
The function doesn't need cursor to be a parameter
The function never executes the query
select_migration_db = "SELECT B.rmt_n, A.prr_id, A.rp_ID FROM mo_TRAC A, T_sft_init_prr B WHERE A.rp_id=B.int_prr_id AND A.STATUS='Sc' AND A.PHASE='first' AND A.WAVE='first'"
def my_query(query):
conn = oracle.connect(user=user,password=pwd,dsn = host,encoding="UTF-8")
cursor = conn.cursor()
cursor.execute(query)
return cursor.fetchall()
rows = my_query(select_migration_db)
for r in rows:
print(r[0])
input("are you ready for the next row?")
The function assumes you've set global variables user, pwd, and host appropriately for your Oracle connection.
select_migration_db = "SELECT B.rmt_n, A.prr_id, A.rp_ID FROM mo_TRAC A, T_sft_init_prr B WHERE A.rp_id=B.int_prr_id AND A.STATUS='Sc' AND A.PHASE='first' AND A.WAVE='first'"
conn = oracle.connect(user=user,password=pwd,dsn = host,encoding="UTF-8")
with conn.cursor() as cursor:
cursor.execute(select_migration_db)
while True:
row = cursor.fetchone()
if row is None:
break
print(row)

python question :sqlite3.ProgrammingError: Cannot operate on a closed cursor

I wrote a database-select function
def select_data():
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
sql = "select VC_FUNDCODE from data_ds limit 100;"
fund_list = cur.execute(sql)
cur.close()
conn.close()
return fund_list
fund_list = select_data()
datalist = []
for item in fund_list:
datalist.append(item)
print(datalist)
Interpreter returns a traceback when i try to call it:
Traceback (most recent call last):
File "/Users/chinalife/Desktop/source/flaskTiantian/database.py", line 70, in
for item in fund_list:
sqlite3.ProgrammingError: Cannot operate on a closed cursor.
Thank you guys, maybe this a simple problem, but I am so happy I could figure it out, here is my corrected code:
#
def select_data():
conn = sqlite3.connect(dbpath)
cur = conn.cursor()
sql = "select VC_FUNDCODE from data_ds limit 100;"
fund_list = cur.execute(sql)
datalist = []
for item in fund_list:
datalist.append(item)
print(datalist)
cur.close()
conn.close()
return datalist
datalist = select_data()
print(datalist)

Python don't return data when joining two tables by a field

I've got a query that returns the data correctly in MySQL but in Python only returns part of the data.
The query is:
select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where
sc.id_fiba = tc.id_player_feb and
tc.id_team_club = 5
This query in MySQL returns 1030 rows like you can see in this screen cap.
However, If I execute this query with python, I've got only 67 rows. This is my code:
connection = pymysql.connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
totalRows = cursor.execute("select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where sc.id_fiba = tc.id_player_feb and tc.id_team_club = %s", [5])
print("Total Rows: " + str(totalRows))
And this is the exit:
Why I've got les data from Python than MySQL?
These are the definition of the tables:
tbl030_shots_chart
tbl006_player_team
Edit I:
With inner join doesn't work in python but works in MySQL
However, with python, still returns 76 rows and not 1030 like MySQL.
connection = pymysql.connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
totalRows = cursor.execute("select sc.* from tbl030_shots_chart as sc inner join tbl006_player_team as pt on sc.id_fiba = pt.id_player_feb and pt.id_team_club = %s", [5])
print("Total Rows: " + str(totalRows))
If I've got the total rows from the cursor with this code:
connection = pymysql.connect(host = DDBB.DDBB_FIBA_HOST,
user = DDBB.DDBB_FIBA_USER,
password = DDBB.DDBB_FIBA_PSWD,
db = DDBB.DDBB_FIBA_NAME,
charset = DDBB.DDBB_FIBA_CHARSET,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
cursor.execute("select sc.* from tbl030_shots_chart as sc inner join tbl006_player_team as pt on sc.id_fiba = pt.id_player_feb and pt.id_team_club = %s", [5])
totalRows = cursor.rowcount
print("Total Rows: " + str(totalRows))
I've got 76 rows returned and not 1030.
You can try creating a view for this query.
CREATE VIEW your_view AS (
SELECT
t1.id,
t1.id_game,
t1.line,
...
t2.id_team_club,
t2.id_player_feb,
...
FROM tbl030_shots_chart t1
LEFT JOIN
tbl006_player_team t2
)
Then in your python code:
sql = 'SELECT * FROM your_view WHERE id_fiba =id_player_feb AND id_team_club = %s'
with connection.cursor() as cursor:
cursor.execute(sql, (5))
Try to use the cursor rowcount attribute:
with connection.cursor() as cursor:
cursor.execute("select sc.* from tbl030_shots_chart sc, tbl006_player_team tc where sc.id_fiba = tc.id_player_feb and tc.id_team_club = %s", [5])
totalRows=cursor.rowcount
print("Total Rows: " + str(totalRows))
In the .execute method there are no return values defined, so you can get anything.

sqlite3 database query in python

I tried performing a search query from the backend of an app I'm working and I got the response below:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
ValueError: parameters are of unsupported type
I have the code below:
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan Number TEXT, Tracing Number TEXT, Submitted By TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", self.NmRqst.text)
rows = cur.fetchall()
conn.close()
return rows
self.NmRqst.text is the QLineEdit that accepts the user input for database query...
Feel free to correct the question as you deem fit!
I have edited the lines of code,
def connectfile(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS PlanInfo (Plan_Number TEXT, Tracing_Number TEXT, Submitted_by TEXT, "
"Location TEXT)")
conn.commit()
conn.close()
def search(self):
conn = sqlite3.connect("TestTrace.db")
cur = conn.cursor()
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
rows = cur.fetchall()
conn.close()
return rows
...and I got the following error:
Traceback (most recent call last):
File "backend.py", line 30, in search
cur.execute("SELECT * FROM PlanInfo WHERE Location=?", str(self.NmRqst.text,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 64 supplied.

Categories

Resources