Reputation: 29
I'm trying to retrieve data from SQL table by entry.get()
function.
def display_1():
global entry_1
x = entry_1.get()
if x =="ball":
objects = cursor.execute("select * from table where stuff=='ball' ")
for row in objects.fetchall():
print("objects =", row[1],row[2],row[3])
I tried the code :objects = cursor.execute("select * from table where stuff==x ")
but it doesn't work. I would use the x variable to retrieve data from database.
the full code is below:
import sqlite3
connection = sqlite3.connect('table.db')
cursor = connection.cursor()
connection.commit()
import tkinter as tk
def display_1():
x = entry_1.get()
if x =="ball":
objects = cursor.execute("select * from table where stuff=='ball' ")
for row in objects.fetchall():
print("objects =", row[1],row[2],row[3])
root = tk.Tk()
entry_1 = tk.Entry(root)
btn_1 = tk.Button(root, text = "Display Text", command = display_1)
entry_1.grid(row = 0, column = 0)
btn_1.grid(row = 1, column = 0)
root.mainloop()
Upvotes: 1
Views: 173
Reputation: 15226
Update: Based on your comments I have changed the function to work directly with the entry field. I used a try/except
statement to handle a failed query.
Try this:
import sqlite3
import tkinter as tk
connection = sqlite3.connect('table.db')
cursor = connection.cursor()
connection.commit()
root = tk.Tk()
entry_1 = tk.Entry(root)
def display_1():
try:
# changed this to follow the safer example in the duplicate post.
objects = cursor.execute("select * from table where stuff=?",(entry_1.get(),))
for row in objects.fetchall():
print("objects = {}".format((row[1], row[2], row[3])))
except:
print("query failed.")
btn_1 = tk.Button(root, text="Display Text", command=display_1)
entry_1.grid(row=0, column=0)
btn_1.grid(row=1, column=0)
root.mainloop()
Upvotes: 1