如何借助where子句和变量从表中获取记录



以下函数用于从sql表中获取所有记录,其中名称(这是一列(等于temp(已分配的变量(

但当我运行该功能时,它显示

mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'temp' in 'where clause'

代码为:

def filter():
global temp
temp = f_dob.get()
print(temp)
my_cursor.execute("SELECT * FROM mk WHERE name = temp")
result=my_cursor.fetchall()
for row in rows:
print(row) 
tree.insert("", tk.END, values=row)

我正在superpreme文本编辑器上编写代码,并在gitbash 上运行它

您需要将tempPython变量绑定到查询:

temp = f_dob.get()
sql = "SELECT * FROM mk WHERE name = %s"
my_cursor.execute(sql, (temp,))
result = my_cursor.fetchall()

此外,您应该小心在prepared语句模式下打开MySQL数据库游标。所以,你的代码应该是这样的:

my_cursor = conn.cursor(prepared=True)

最新更新