我正在使用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格式约定,当我使用此格式时,单个execute函数正在起作用:
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()
编辑:
我已经阅读了官方的documentation。我复制并粘贴了代码并将其更改为我的参数,但仍然无法使用。
categories = [('Test1'),('Test2'),]
stmt = "INSERT INTO categories (name) VALUES (%s)"
cursor.executemany(stmt, categories)
仅排除基础:
[我看到您在问题中粘贴的for
循环以database.commit()
语句结尾,但是executemany
块没有。您是在代码中还是在问题中忽略了这一点? (对不起,我将此作为答案。.还不能添加评论)
关于此stackoverflow question的解决方案,我找到了解决方案。
该陈述是正确的,但我的数据列表错误。如果只提供一个值,则需要在元组中使用逗号。
这是最终解决方案:
categories = [('Test1',),('Test2',)]
stmt = "INSERT INTO categories (name) VALUES (%s)"
cursor.executemany(stmt, categories)
这也记录在MySQL文档中。