Python SQLite库存管理系统:查询记录输出None问题求助
解决你的库存管理系统查询问题
我看了你的代码,问题主要出在结果集的读取逻辑和几个细节疏漏上,咱们一步步拆解修复:
核心问题分析
重复读取结果集导致返回None
你先用cursor.fetchall()判断记录是否存在,这个方法会一次性取出所有查询结果,把游标直接移到结果集末尾。之后再调用fetchone()时,已经没有剩余记录可读取,自然返回None。未正确调用cursor的fetchone方法
代码里的print(fetchone())少了cursor.前缀,这会直接抛出NameError(除非全局定义了这个函数,但显然没有),正确写法是cursor.fetchone()。found变量逻辑失效
找到食材后你没有把found设为1,导致循环会一直重复,即使查询到结果也会反复让用户输入。提示文字错误
重试提示写的是"Enter another Retailer",但用户是在查询食材,改成"Enter another ingredient"更准确。
修复后的代码
import sqlite3 import time def searchIngredient(): found = 0 while found == 0: ingredient = input("Enter an ingredient name: ") if len(ingredient) < 3: print("Ingredient name must be three or more characters long") continue with sqlite3.connect("Inventory.db") as db: cursor = db.cursor() # 明确指定要返回的字段,避免不必要的数据 findIngredient = "SELECT Ingredient, stock_level, Price, Retailer FROM Inventory WHERE Ingredient=?" cursor.execute(findIngredient, (ingredient,)) # 直接获取单条匹配记录(建议给Ingredient字段加唯一约束,避免重复数据) record = cursor.fetchone() if record: # 格式化输出,让结果更易读 print("\n✅ Found ingredient record:") print(f"Ingredient: {record[0]}") print(f"Stock Level: {record[1]}") print(f"Price: {record[2]}") print(f"Retailer: {record[3]}") found = 1 # 找到后标记为已完成,退出循环 else: print("❌ Ingredient does not exist in Inventory") tryAgain = input("Do you want to enter another ingredient? Y or N ") if tryAgain.lower() == "n": mainMenu() time.sleep(2) mainMenu() # 示例主菜单函数(替换成你自己的实现即可) def mainMenu(): print("\n--- Main Menu ---") # 这里添加你的主菜单逻辑
额外优化建议
- 如果你的
Inventory表允许同名食材(不推荐),可以改用fetchall()获取所有匹配结果并遍历输出:records = cursor.fetchall() if records: print(f"\nFound {len(records)} matching records:") for idx, record in enumerate(records, 1): print(f"\nRecord {idx}:") print(f"Ingredient: {record[0]}") print(f"Stock Level: {record[1]}") print(f"Price: {record[2]}") print(f"Retailer: {record[3]}") found = 1 - 建议给
Ingredient字段添加唯一约束(CREATE TABLE Inventory (..., Ingredient TEXT UNIQUE, ...)),避免重复数据,让查询逻辑更简洁。
内容的提问来源于stack exchange,提问作者georginaa_07
相关产品推荐
相关产品推荐

