python - 如何在 sqlite 中选择一行名称,而不是使用 python 的 id?
问题描述
我正在使用 sqlite 作为数据库在 python 中编写商店管理系统。我希望在输入商品名称而不是商品 ID 时能够看到商品价格...下面是代码片段
def ajax2(self, *args, **kwargs):
self.get_name = self.entername_e.get()
#get the products info with that name or id and fill labels above
query = "SELECT * FROM inventory WHERE name=?"
result = c.execute(query, (self.get_name, ))
for self.r in result:
self.get_name = self.r[1] #name
self.get_price = self.r[4] #sp
self.get_stock = self.r[2] #stock
self.productname.configure(text="Product's Name: "+ str(self.get_name))
self.pprice.configure(text="Price: Gh "+str(self.get_price))
每当我在标签条目中输入名称后运行代码时,即使该名称不在数据库中,也会出现该名称,并且命令行中会出现一条错误消息,如下所示:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\GH\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in
__call__
return self.func(*args)
File "main.py", line 96, in ajax2
self.pprice.configure(text="Price: Gh "+str(self.get_price))
AttributeError: 'Application' object has no attribute 'get_price'
PS C:\Users\GH\Desktop\Developments\Store Management Software>
解决方案
如果数据库中不存在该名称,则查询返回的游标为空并且不进入循环。结果,self.get_name
未更改并保留输入的值,并且self.get_price
未设置,因此出现错误。
你应该明确地测试这种情况:
...
result = c.execute(query, (self.get_name, ))
empty = True
for self.r in result:
empty = False
self.get_name = self.r[1] #name
self.get_price = self.r[4] #sp
self.get_stock = self.r[2] #stock
if empty: // name is not present in database
...
推荐阅读
- python - Tkinter mainloop坏了,消息框不断弹出
- android - 搜索 android Gradle 的依赖项
- excel - 在visual studio中动态创建tablix
- java - 是否可以使用 javapreparedstatement SQL 搜索 MySQL 工作台数据库中的所有表以更改值?
- python - for循环的高级使用
- amazon-web-services - 如何通过入口控制器在 Kuberenetes 中公开内部服务
- javascript - NestJS 在服务类中丢失了这个内部函数方法的上下文
- c# - 监控本地网络的流量,每台计算机
- amazon-web-services - 在 Lambda 内存与临时缓存中缓存 JWKS
- split - 我想知道我是否可以使用正则表达式或其他任何方法来分隔字符串?