我正在尝试通过entry.get()
函数从SQL表检索数据。
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])
我尝试了以下代码:objects = cursor.execute("select * from table where stuff==x ")
但这不起作用。我将使用x变量从数据库中检索数据。
完整代码如下:
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()
答案 0 :(得分:0)
更新:根据您的评论,我更改了功能以直接与输入字段一起使用。我使用了try/except
语句来处理失败的查询。
尝试一下:
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()