【问题标题】:Multiplying columns in SQLite3 from two different tables从两个不同的表中乘以 SQLite3 中的列
【发布时间】:2021-03-10 12:05:39
【问题描述】:

我目前正在从事一个学校项目,我必须使用 Python、Tkinter 和 SQLite3 开发具有图形用户界面的数据库应用程序。用户在表单中输入 ProductID 和数量,我试图让程序使用 ProductID 从产品表中选择产品的价格,并将此价格乘以用户输入的数量,得到总成本并将此结果插入到订单表的总计字段中。

我收到以下错误:

  File "c:\Users\Ryan\OneDrive - C2k\A2 2020-2021\Computer Science\A2 Unit 5\Code\OrderForm.py", line 81, in CalculatePrice
    price = ((int(quantity)*(int(x) for x in results)))
TypeError: unsupported operand type(s) for *: 'int' and 'generator'

我已经对此错误进行了研究,但是,我仍然无法理解如何使其工作,甚至是否可能。如果有人可以查看我下面的代码并尝试帮助我完成此操作,我将不胜感激。

    def CalculatePrice(self):
        orderid = self.OrderIDEntry.get()
        productid = self.ProductIDEntry.get()
        quantity = self.QuantityEntry.get()
        with sqlite3.connect("LeeOpt.db") as db:
            cursor = db.cursor()
            searchprice = ('''SELECT Price FROM Products WHERE ProductID = ?''')
            cursor.execute(searchprice, [(productid)])
            results = cursor.fetchall()
            
            if results:
                for i in results:
                    price = ((int(quantity)*(int(x) for x in results)))
                    addprice = ('''INSERT INTO Orders(OrderTotal)
                    VALUES (?)''')
                    cursor.execute(addprice, [(price)])
                    self.ClearEntries()
            else:
                tkinter.messagebox.showerror("Error", "No product was found with this ProductID, please try again.")
                self.ClearEntries()

【问题讨论】:

  • 假设ProductID 是唯一的,searchprice 将返回一个价格...您在results 上循环多次。 price = int(searchprice[0][0]) * int(quantity) 应该足够了。
  • 你应该细分任务。首先尝试使用具有给定产品 ID 的产品价格设置一个变量。 然后对该产品进行计算,然后将结果插入到订单表中。检查成功 e. G。每个步骤都有“打印”。
  • @MauriceMeyer 是的 ProductID 是唯一的。我明白你的解释,谢谢!我现在就试试这个。
  • @MichaelButscher 我明白了,谢谢你的解释。

标签: python database sqlite


【解决方案1】:

您在 results 可迭代对象上混合了一个外部循环,一次插入 1 个值,并在值的可迭代对象上执行相同的 INSERT 查询。

第一种方式,外部循环(我删除了一些无用的括号):

            for i in results:
                price = int(quantity)*int(i)
                addprice = ('''INSERT INTO Orders(OrderTotal)
                VALUES (?)''')
                cursor.execute(addprice, [price])

第二种方式,使用executemany

            prices = ([int(quantity)*int(x)] for x in results)  # prices is an iterable of lists
            addprice = ('''INSERT INTO Orders(OrderTotal)
            VALUES (?)''')
            cursor.executemany(addprice, prices)

但是如果你正在学习 SQL 和数据库访问,你可以直接使用联合查询:

addprice = '''INSERT INTO Orders(OrderTotal)
    SELECT :quantity * Price FROM Products
    WHERE Products.ProductID = :productid'''
cursor.execute(addprice, {'quantity': quantity, 'productid': productid})

由于您的代码包含一个(未使用的)orderid 变量,我认为您想要的是:

addprice = '''INSERT INTO Orders(OrderID, OrderTotal)
    SELECT :orderid, :quantity * Price FROM Products
    WHERE Products.ProductID = :productid'''
cursor.execute(addprice, {'quantity': quantity, 'productid': productid,
                          'orderid': orderid})

【讨论】:

    【解决方案2】:

    您的表达式(int(x) for x in results)(int(quantity)*(int(x) for x in results)) 计算为生成器对象,因为您将其括在括号中。看这里

    >>> (quant for quant in range(5))
    <generator object <genexpr> at 0x1021e1780>
    >>>
    

    因此,删除括号并将其分解为更小的块。 此外,单个 productId 应该只返回一个价格,因此您循环多次并且不必使用元组,除非您输入的本身是多个产品 ID,并且您将每个价格和产品相乘并计算订单全部的。 简化版可能如下所示

            cursor.execute('SELECT Price FROM Products WHERE ProductID = ?', (productid,))
            result = cursor.fetchone()
            
            if result:
                price = quantity * float(result[0])
                cursor.execute('INSERT INTO Orders(OrderTotal) VALUES (?)', (price,))
                self.ClearEntries()
            else:
                tkinter.messagebox.showerror("Error", "No product was found with this ProductID, please try again.")
                self.ClearEntries()
    

    【讨论】:

    • 我在运行此代码时收到以下错误。任何想法为什么? ` 文件“c:\Users\Ryan\OneDrive - C2k\A2 2020-2021\Computer Science\A2 Unit 5\Code\OrderForm.py”,第 79 行,CalculatePrice 价格 = 数量 * 浮动(结果)类型错误:浮动( ) 参数必须是字符串或数字,而不是“元组”`
    • 是的,row/result 是一个元组对不起,所以你需要检索第一个元素,result[0] 应该返回价格。
    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多