gpt4 book ai didi

python-3.x - 如何通过entry.get()变量从SQL检索数据

转载 作者:行者123 更新时间:2023-12-03 08:09:57 24 4
gpt4 key购买 nike

我正在尝试通过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()

最佳答案

更新:根据您的评论,我更改了功能以直接与输入字段一起使用。我使用了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()

关于python-3.x - 如何通过entry.get()变量从SQL检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com