mysql.connector.errors.InternalError: Unread result found - python-3.x

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

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

how to fetch data stored in sqlite3 database and assign it to the variables in tkinter python

In the code below I saved value1 and value2 to the sqlite3 database and txt_ in folder named data.
What I am trying to achieve here is that when I rerun the programme and open the file, txt_ file should be open in the text area with the lines I added when I saved it. And when I click add button, value1 and value2 should be updated and newly created line should be in the next line.
Let me know if my method is correct, if not then please tell me the better one.
CODE:
from tkinter import *
from tkinter import messagebox
import sqlite3
import os
root = Tk()
root.geometry('400x400')
var_e = StringVar(None)
def create_my_db():
conn = sqlite3.connect(database=r'my db.db')
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS "myLogs"
(
"int_value" INTEGER,
"float_value" REAL
)
""")
conn.commit()
create_my_db()
def add_lbl():
global value1, value2
value1 += 1
value2 += 1
sample = f'This is line {value1} which has value of {value2}\n'
txt_.insert(END, sample)
def save():
conn = sqlite3.connect(database=r'my db.db')
cur = conn.cursor()
cur.execute("""INSERT INTO myLogs VALUES (?,?)""",
(
value1,
value2
)
)
conn.commit()
# labels to check if the values are stored in the database
values_lbl.config(text=f'value 1 is [ {value1} ] & value 2 is [ {value2} ]')
def save_txt():
file_txt = open(f'data/{value1}.txt', 'w')
file_txt.write(txt_.get(1.0, END))
file_txt.close()
messagebox.showinfo('SAVED', 'Data saved to the database.')
def open_():
for txt_file in os.listdir("data/"):
if txt_file.split('.')[0] == f'{var_e.get()}':
file_ = open(f"data/{txt_file}", "r")
for i in file_:
txt_.insert(END, i)
file_.close()
value1 = 0
value2 = 0.9
values_lbl = Label(root, text=f'value 1 is [ {value1} ] & value 2 is [ {value2} ]')
values_lbl.pack()
btn_frame = Frame(root)
btn_frame.pack()
btn_add = Button(btn_frame, text='Add', command=add_lbl)
btn_add.pack(side=LEFT)
e = Entry(btn_frame, textvariable=var_e)
e.pack(side=LEFT)
btn_open = Button(btn_frame, text='Open', command=open_)
btn_save = Button(btn_frame, text='Save', command=lambda:[save(), save_txt()])
btn_open.pack(side=LEFT)
btn_save.pack(side=LEFT)
txt_ = Text(root)
txt_.pack(fill=BOTH, expand=True)
root.mainloop()
When I posted this question I didn't know how to run the query to update value1 and value2, that's why I didn't mention the query in open_() function. Now I came to know how that query should have been done. So in the below code I added the query to open_() function. Now the complete programme runs fine.
def open_():
global value1, value2
txt_.delete(1.0, END)
for txt_file in os.listdir("data/"):
if txt_file.split('.')[0] == f'{var_e.get()}':
file_ = open(f"data/{txt_file}", "r")
for i in file_:
txt_.insert(END, i)
file_.close()
conn = sqlite3.connect(database=r'my db.db')
cur = conn.cursor()
cur.execute("""SELECT * FROM myLogs WHERE int_value=?""", (var_e.get(),))
row = cur.fetchone()
if row is None:
messagebox.showerror("ERROR", 'Invalid input.')
else:
value1 = row[0]
value2 = row[1]
conn.commit()

table as var in cur.execute

I'm noob at python, and I'm trying to do some operations in some tables.
At the moment I'm doing this with hard coding the tables:
cur.execute("select id,email from table1;")
but I'm want to change the tables to and variable to construct a function, like:
cur.execute("select id,email from table;")
How I can do this?
Many thanks
I'm using python3 with psycopg2
#open connection with db
conn = psycopg2.connect(host="localhost",database="test", user="test", password="test")
cur = conn.cursor()
#Select id
cur.execute("select id,email from customers;")
#put ids on list
row = cur.fetchone()
Also I tried this:
sql = "select id,email from %s"
val = customers
cur.execute(sql, val)
And I have this error:
File "updateemails.py", line 14, in <module>
val = (customers)
NameError: name 'customers' is not defined```

how to translate datebase tables(sqlite3) to numpy array

a datebase contained 80 tables ,every table is a 18000x4 matrix ,how can I translate these to a 80x18000x4 numpy array?
the db : https://drive.google.com/open?id=0B3bNSNFik5wGdm1DYnJwNHBJMVU
I wrote a function. Do you have any better idea?
import sqlite3 as sql
import os
def db_to_array(db,r,c):
db = sql.connect(db)
cursor = db.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
wd=os.getcwd()
if not os.path .exists(wd +'/temp/'):
os.makedirs(wd +'/temp/')
for table_name in tables:
table_name = table_name[0]
table = pd.read_sql_query("SELECT * from %s" % table_name, db)
table.to_csv(wd +'/temp/'+ table_name + '.csv', index_label='index')
ss=os.listdir(wd +'/temp/')
print(len(ss))
dd=np.empty([len(ss),r,c])
for i in range(len(ss)):
ddd=np.array(pd.read_csv(wd +'/temp/'+ss[i]))
print(i)
print(ddd.shape)
dd[i,:,:]=ddd[:,0:r]
return dd

How to delete data based on rowid

Using python, how do i get to delete data based on lastrowid. The code i have deletes all the rows
CODE:
import re
import sys
import difflib
import sqlite3
def main():
while True:
name = input ('Please Type your Question: ').lower().split()
name2 = name[:]
import sqlite3
for item in name2:#break
conn = sqlite3.connect("foods.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO INPUT33 (NAME) VALUES (?);", (name2,))
cursor.execute("select MAX(rowid) from [input33];")
conn.commit()
for rowid in cursor:break
for elem in rowid:
m = elem
print(m)
cursor.execute("DELETE FROM INPUT33 (NAME) WHERE NAME = name")
To get the last inserted rowid, use the cursor's lastrowid attribute.
To delete a record with a specific rowid, use that column in the WHERE condition:
cursor.execute("INSERT INTO input33(Name) VALUES(?)", ("whatever",))
rowid = cursor.lastrowid
cursor.execute("DELETE FROM input33 WHERE rowid = ?", (rowid,))

Resources