首页 > 解决方案 > 执行 executemany() 时,并非所有参数都在 SQL 语句中使用

问题描述

我正在使用 mysql-connector 的 Python3 版本,并尝试使用 executemany 函数。

我的代码如下所示:

database = mysql.connector.connect(
        host='localhost',
        user='user',
        password='test',
        database='test_database'
    )
cursor = database.cursor()
categories = ['Test1', 'Test 2']
stmt = "INSERT INTO categories (name) VALUES (%s)"
cursor.executemany(stmt, categories)

我的表只有一列,这是一个名为 name 的字符串列。

我尝试将列表中的条目用作元组,我将插入语句更改为:

stmt = "INSERT INTO categories (name) VALUES ('%s')"

所以我基本上在 %s 占位符中添加了单引号。我还尝试将 %s 替换为 ? 但这也没有用。

由于 Python3 格式约定,当我使用这个时,单个执行函数正在工作:

stmt = "INSERT INTO categories (name) VALUES ('{}')".format('Test1')

不幸的是,executemany 函数需要第二个参数,所以我不能使用 .format 函数。

这是我使用正常执行功能的工作示例:

database = mysql.connector.connect(
            host='localhost',
            user='user',
            password='test',
            database='test_database'
        )
cursor = database.cursor()
categories = ['Test1', 'Test2']
for category in categories:
    cursor.execute("INSERT INTO categories (name) VALUES ('{}')".format(category))

database.commit()

编辑:

我已经阅读了官方文档。我复制并粘贴了代码并将其更改为我的参数,但它仍然不起作用。

categories = [('Test1'),('Test2'),]
stmt = "INSERT INTO categories (name) VALUES (%s)"
cursor.executemany(stmt, categories)

标签: mysqlpython-3.xmysql-connector-python

解决方案


只是为了排除基础知识:

我看到for您在问题中粘贴的循环以database.commit()语句结尾,但executemany块没有。您是在代码中还是在问题中忽略了这一点?(对不起,我把这个作为答案..还不能添加评论)


推荐阅读