SQLite,Python和列表

时间:2016-03-16 20:46:13

标签: python list sqlite iterator

我是Python和SQLite的新手,但我有一个程序,我希望用户输入他们想从数据库表中订购的项目数。他们输入产品和数量,选择查询应返回匹配的项目。它的工作原理除了它只打印出最后一个用户条目而不是所有用户条目。我认为问题在于选择查询行,但我无法弄明白。我尝试了很多变化但它崩溃或只返回最后一个用户条目。

enter code here
for i in range(orderQty):
    prodItem = int(input("Enter your Item to the List: "))
    userOrder.append(prodItem)
    prodQty = int(input("Enter the item quantity: "))
    userQty.append(prodQty)


for j in range(len(userOrder)):
    cursor = connection.execute("SELECT GTINnum, Item, CurrentStock,Cost from orderFile WHERE GTINnum= ?", (prodItem,))


    for row in cursor:
        print ("GTINnum =", row[0], "Item = ", row[1], "Cost = ", row[2], "Qty Ordered=",(prodQty), "\n")
        prodCost = prodQty * row[2]
        print ("Total product cost is: ", (prodCost))

1 个答案:

答案 0 :(得分:1)

在块中

for j in range(len(userOrder)):
    cursor = connection.execute("SELECT GTINnum, Item, CurrentStock,Cost from orderFile WHERE GTINnum= ?", (prodItem,))
    for row in cursor:
        print ("GTINnum =", row[0], "Item = ", row[1], "Cost = ", row[2], "Qty Ordered=",(prodQty), "\n")
        prodCost = prodQty * row[2]
        print ("Total product cost is: ", (prodCost))

您反复使用上一个用户输入prodItemprodQty。替换为通过之前构建的列表进行迭代的内容:

for j in range(len(userOrder)):
    cursor = connection.execute("SELECT GTINnum, Item, CurrentStock,Cost from orderFile WHERE GTINnum= ?", (userOrder[j],))
    for row in cursor:
        print ("GTINnum =", row[0], "Item = ", row[1], "Cost = ", row[2], "Qty Ordered=",userQty[j], "\n")
        prodCost = userQty[j] * row[2]
        print ("Total product cost is: ", (prodCost))

也许我错过了一些事情,但是你应该清楚你被困在哪里......

更新:当您只想进行一次选择时,您必须生成一系列?,例如由

q = "(" + ",".join(["?" for x in userOrder]) + ")"

并将其附加到以in结尾的查询中。您还必须将list userOrder转换为元组。但是,与prodQty中的条目顺序相比,调整结果的顺序变得复杂。简单地将数组作为参数传递并期望它“展开”=in将不起作用。如果你不想彻底改变你的程序,我不会试图这样做。