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

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)

Related

issue with deleting rows in python sqlite [duplicate]

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.

Sqlite3 Change position column (reordering)

I have made this python method:
def move_player_list_item(start_position,end_position,player_list_item):
conn = create_connection()
query = "DELETE FROM `player_list` WHERE `position`=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),))
conn.commit()
if start_position<end_position:
query = "UPDATE `player_list` SET `position`=`position`-1 WHERE `position`>? AND `position`<=?;"
cur = conn.cursor()
cur.execute(query,(str(start_position),str(end_position)))
conn.commit()
elif end_position<start_position:
query = "UPDATE `player_list` SET `position`=`position`+1 WHERE `position`>=? AND `position`<?;"
cur = conn.cursor()
cur.execute(query,(str(end_position),str(start_position)))
conn.commit()
query = query = "INSERT INTO `player_list` (`play`, `relative_type`, `relative_number`, `repeats`, `duration_milliseconds`, `duration_human`,`position`) VALUES (?,?,?,?,?,?,?)"
cur = conn.cursor()
cur.execute(query,(str(player_list_item["play"]),str(player_list_item["relative_type"]),str(player_list_item["relative_number"]),str(int(player_list_item["repeats"])),str(int(player_list_item["duration_milliseconds"])),str(player_list_item["duration_human"]),str(end_position)))
conn.commit()
return 1
When start_position<end_position works with no error.
But when end_position<start_position there is an error:
Traceback (most recent call last):
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 977, in <module>
main()
File "C:\Users\Χρήστος Παππάς\Έγγραφα\projects\Papinhio player\Αρχεία βάσης δεδομένων (Sqlite3)\Έλεγχος συναρτήσεων sqlite3 (check sqlite3 functions).py", line 925, in main
sqlite3_functions.move_player_list_item(30,20,player_list_items_db[29])
File "C:/Users/Χρήστος Παππάς/Έγγραφα/projects/Papinhio player/Αρχεία βάσης δεδομένων (Sqlite3)/../Αρχεία πηγαίου κώδικα εφαρμογής (Python)/Αρχεία κώδικα python (Python files)/Συναρτήσεις sqlite3 (Sqlite3 functions).py", line 1125, in move_player_list_item
cur.execute(query,(str(end_position),str(start_position)))
sqlite3.IntegrityError: UNIQUE constraint failed: player_list.position
The only solution i have thought about is to remove the unique constraint.
Is there any better solution?

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.

Get items from a database tuple in Python

This is my code:
import pymysql
def connect():
print("connect to database")
pw = input("Password: ")
conn = pymysql.connect(host='localhost', port=3306,
user='root', passwd=pw, db='contacts')
conn.autocommit(True)
cur_ = conn.cursor()
return cur_
def show_tables(self):
print("show tables: ")
self.execute("""SHOW TABLES""")
print(self.fetchall())
return self.fetchall()
db = connect()
table_names = show_tables(db) # returns a tuple
print(len(table_names)) # output zero
table_name = table_names[0][0] # ? - todo - get item from tuple
show_tables() return the value (('person',),).
I want to get the name person with table_names[0][0]. But this doesn't work. Also the length of (('person',),) is 0. But why?
Edit:
I get the error:
Traceback (most recent call last):
File "/home/kame/Dropbox/code/python/scripts/database.py", line 65, in <module>
table_name = table_names[0][0] # ? - todo - get item from tuple
IndexError: tuple index out of range
It looks like show_tables(self) is returning null, a list on None object, because you can only call one time cursor.fetchall().
The solution : comment the line
print(self.fetchall())

opening and closing mysql connection

I have this python function:
import MySQLdb as mdb
def sql_query(sql):
try:
con = mdb.connect('localhost', 'user', '', 'dbs')
with con:
cur = con.cursor()
cur.execute(sql)
results = cur.fetchall()
return results
except mdb.Error, e:
sys.exit(1)
finally:
if con:
con.close()
then i have loads of code that calls this function, sometime the con closes and i get this traceback:
Traceback (most recent call last):
File "users.py", line 431, in <module>
orders = get_orders(user_id, mongo_user_id, address_book_list)
File "users.py", line 343, in get_orders
order_lines = get_order_lines(order_id)
File "users.py", line 288, in get_order_lines
for item in sql_query(get_order_lines_sql):
File "users.py", line 57, in sql_query
if con:
UnboundLocalError: local variable 'con' referenced before assignment
where my get_orders code is like:
def get_orders(user_id, mongo_user_id, address_book_list):
# we just want orders that are less than 2 years old
get_orders_sql = """SELECT order_id, state, state2, stamp, reference, comments, address_id, delivery_id, user_id FROM user_orders WHERE address_id IS NOT NULL and stamp >= '2012-01-01 00:00:00' and user_id='%s' ORDER BY stamp DESC"""% (user_id)
# delivery_id - this is the shipping option the user chose.
for items in sql_query(get_orders_sql):
#print items
order_id = items[0]
there is about 50K rows in the orders
any advice much appreciated
you need to initialize con since let say there was error in mdb.connect your get error when it some how reaches final your con is still un initialized
import MySQLdb as mdb
def sql_query(sql):
con='' #this should be intiated
try:
con = mdb.connect('localhost', 'user', '', 'dbs')
with con:
cur = con.cursor()
cur.execute(sql)
results = cur.fetchall()
return results
except mdb.Error, e:
sys.exit(1)
finally:
if con:
con.close()

Categories

Resources