无法处理参数:builtin_function_or_method(<built-in function id>),它必须是列表、元组或字典类型

问题描述 投票:0回答:1

Python/MySQL(以及编程!)的全新体验。创建程序来存储食物的营养成分。然后每天创建一个消耗的食物表,该表将操纵食物表中的值。成功创建了添加、检查和删除食物的例程。现在尝试从食物表中提取一种食物并得到上述错误。附上代码:

import mysql.connector

def get_foods_detail(category):
    try:
        connection = mysql.connector.connect(host='localhost',
                                             database='nutrition',
                                             user='root',
                                             password='631150#?ioB')

        cursor = connection.cursor()
        sql_select_query = """select * from foods where category = %s"""
        # set variable in query
        cursor.execute(sql_select_query, (category,))
        # fetch result
        record = cursor.fetchall()

        for row in record:
            print("Id  ", row[0], "CATEGORY:  ", category.rstrip(), "TYPE:  ", row[2
                  ], "BRAND: ", row[3], "SELLER: ", row[4], "Kcal: ", row[7])                                                      
                       
        choose = input("Input id of food consumed ")
        choose = int(choose)
        choose = [choose]
        print(choose)
        sql_select_query = """ select * from foods where id = choose"""
        cursor.execute(sql_select_query,(id))
        record = cursor.fetchone()
        print(record)
        user_input = ("Correct record? y/n") **This is as far as I've got**
    except mysql.connector.Error as error:
        print("Failed to get record from MySQL table: {}".format(error))

    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection is closed")

category = input("Enter Food Category: ")
get_foods_detail(category)

期望显示输入的 id 的记录,以便用户检查它是否正确。 尝试在网上解释可能的解决方案,并尝试各种使用括号等。花了整个上午的时间 - 现在卡住了, 我们将不胜感激。

python
1个回答
0
投票

您实际上并没有参数化您的查询。您应该使用一些占位符,而不是 SQL 查询中的硬编码字符串

choose

sql_select_query = """ select * from foods where id = %s"""

现在,当您执行查询时,

execute
的第二个参数应该是由choose构造的
tuple

choose = int(input("Input id of food consumed "))
cursor.execute(sql_select_query, (choose,))

(请注意尾随的公共端;

(choose)
相当于
choose
,并且
execute
必须 具有某种可迭代性,即使查询只有一个占位符需要填充。)

(我知道在你的原始代码中你重新定义了

choose = [choose]
来创建一个可迭代对象,但更清楚的是不重用这样的名称。choice是一个整数;在对
execute的调用中明确元组/列表/等
。)

© www.soinside.com 2019 - 2024. All rights reserved.