gpt4 book ai didi

python - 只从 mysql 获取最后一个值

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:46 27 4
gpt4 key购买 nike

我有一个代码,它需要显示数据库中与输入框中输入的数据相同的值的标签。但我只得到显示的标签的最后一个值而不是第一个值。

数据库:

a1 bike  
a2 car

问题:如果我输入 a1,自行车没有显示..但是当我输入 a2 时我得到了汽车。

编码:

import Tkinter as tki
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="mysql", # your password
db="sakila") # name of the data base
cursor = db.cursor()

# execute SQL select statement
cursor.execute("SELECT A1,A2 FROM adarsh1")
keywords1=[]
for i in cursor.fetchall():
keywords1.append(i[0])
keywords1.append(i[1])

class App(object):
def __init__(self,root):
self.root = root

self.txt_frm = tki.Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)
button3 = tki.Button(self.txt_frm,text="CLICK 1", command = self.retrieve_inpu)
button3.grid(column=0,row=2)
self.entry = tki.Entry(self.txt_frm)
self.entry.grid(column=1,row=0)

#create label in init
self.label = tki.Label(self.txt_frm)
self.label.grid(column=0,row=3)

def retrieve_inpu(self):
ent = self.entry.get()

if ent in i[0]:
self.label['text'] = i[1]


root = tki.Tk()
app = App(root)
root.mainloop()

最佳答案

在构建 keywords1 时,您正在使用 i 作为循环变量:

for i in cursor.fetchall():
keywords1.append(i[0])
keywords1.append(i[1])

i 永远不会被清除,它仍然绑定(bind)到数据库的最后一行。

然后您重新使用该全局名称:

def retrieve_inpu(self):
ent = self.entry.get()

if ent in i[0]:
self.label['text'] = i[1]

因为 i 仍然设置为 ['a2', 'car'] 上面的 if 语句只有在 ent 设置为 'a2''a''2' 之一。

您可以改用字典:

keywords1 = {}
for row in cursor.fetchall():
keywords1[row[0]] = row[1]

现在您正在将值从第一列映射到第二列。在您的 retrieve_inpu 函数中,如果键存在,您现在可以简单地查找值:

def retrieve_inpu(self):
ent = self.entry.get()

if ent in keywords1:
self.label['text'] = keywords1[ent]

这只会匹配整个单词,所以只有 'a2''a1' 可以。

最好的方法是向数据库请求匹配:

def retrieve_inpu(self):
ent = self.entry.get()

cursor.execute('SELECT A2 FROM adarsh1 WHERE A1=%s', (ent,))
row = cursor.fetchone()
if row:
self.label['text'] = row[0]

这再次只匹配整个单词;仅当存在与 A1 完全匹配的行时,才能返回该行。要使其适用于子字符串匹配,您可以使用 LIKE 查询:

def retrieve_inpu(self):
ent = self.entry.get()

cursor.execute('SELECT A2 FROM adarsh1 WHERE A1 LIKE %s', ('%{}%'.format(ent),))
row = cursor.fetchone()
if row:
self.label['text'] = row[0]

关于python - 只从 mysql 获取最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27657418/

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