mysql - 执行 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)
解决方案
只是为了排除基础知识:
我看到for
您在问题中粘贴的循环以database.commit()
语句结尾,但executemany
块没有。您是在代码中还是在问题中忽略了这一点?(对不起,我把这个作为答案..还不能添加评论)
推荐阅读
- node.js - TypeError:user.findOne 不是我模型上的函数
- python - 将 DataFrame 的结果输出到 QLabel
- python - 模拟内部方法 Python2
- javascript - 日历显示今天的当前日期以及接下来的 60 天
- java - 给定类的 Gson 序列化器(如果在另一个特定类中)
- .net-core - 在 TeamCity 中构建特定 .NET Core 项目时引用传递依赖项的问题
- c# - CodedUI,SpecFlow:尝试从按钮获取菜单选项
- hana - SAP HANA SDI ECC 源与 HANA 表增量
- java - Getter 返回旧值
- php - 将 Laravel 项目迁移到新实例后 POST 和 GET 错误。原因是什么?