【问题标题】:SQLite, Python and listsSQLite、Python 和列表
【发布时间】:2016-03-16 20:46:12
【问题描述】:

我是 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))

【问题讨论】:

  • 缩进还是不行。请使用您的编辑器将您的代码缩进 4 个空格,然后粘贴到问题中。让生活更轻松;)
  • 尝试将userOrder[j] 作为选择的参数,而不是prodItem。与prodQty 类似,进一步向下。取而代之的是userQty[j]
  • IDLE 告诉我缩进是 4 个空格?
  • userOrder[j] 抛出 ValueError: parameters are unsupported type
  • 请尝试答案中的代码

标签: python list sqlite iterator


【解决方案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是行不通的。如果你不想完全改变你的程序,我不会尝试那样做。

【讨论】:

    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    相关资源
    最近更新 更多