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

时间:2018-10-17 13:18:17

标签: python-3.x tkinter sqlite

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

1 个答案:

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