首页 > 解决方案 > 如何在 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> 

标签: pythonmysqlsqlitetkinter

解决方案


如果数据库中不存在该名称,则查询返回的游标为空并且不进入循环。结果,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
        ...

推荐阅读