[英]Not all parameters were used in the SQL statement but I just want to update 1 column
我有一个要插入到mySQL数据库中的文件名列表。 我已经完成以下工作:
cur.executemany("""INSERT INTO table (filename) VALUES(%s)""", folder_files)
但是,我得到:mysql.connector.errors.ProgrammingError:并非在SQL语句中使用了所有参数。
数据库中的表确实有3列,但我只想将数据插入文件名列。
我的替代(有效)代码是
for each_pdf_file in folder_files:
cur.execute("INSERT INTO table (filename) VALUES(%s)", (each_pdf_file,))
print(each_pdf_file)
但这非常慢(我有成千上万个文件要导入数据库)。
那么我该如何使用executemany? 还是我必须遵守替代代码?
我猜你的folder_files
看起来像这样(字符串列表):
folder_files = ["folder1", "folder2", "folder3"]
但实际上应该看起来像这样(一个字符串元素元组的列表):
folder_files = [("folder1",), ("folder2",), ("folder3",)]
您可以通过列表理解功能轻松地将列表转换为正确的格式:
folder_files = [(folder,) for folder in folder_files]
这是文档中的相关部分,提示您应始终将参数放在元组中:
注意
在Python中,包含单个值的元组必须包含逗号。 例如,
('abc')
被评估为标量,而('abc',)
被评估为元组。
您没有足够的格式字符串来进行sql查询。
format_string = ('%s, '* len(folder_files))[:-2]
cur.executemany("INSERT INTO table (filename) VALUES({})".format(format_string), folder_files)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.