使用 Python 和 pypyodbc 的 MSSQL 数据插入 - 参数必须在列表、元组中

MSSQL data insertion with Python and pypyodbc - Params must be in a list, tuple

我正在尝试将(我可以很好地读取)值写入 MSSQL 实例。我的代码类似于:

import pypyodbc
lst = ['val1', 'val2', 'val3']
connection = pypyodbc.connect(...)
cursor = connection.cursor()
cursor.executemany("INSERT INTO table (a, b, c)VALUES(?,?,?)", lst)

这个returns: 参数必须在列表、元组中。我读过类似的帖子,建议尝试 lst = list(['val1, 'val2', val3']) 但是这个 returns: list() 最多接受 1 个参数(给定 3 个) 我也试过 cursor.execute() 的变体,但同样的问题。

注意cursor.execute的区别:

.execute ( operation [, parameters ])

Parameters may be provided as sequence or mapping and will be bound to variables in the operation.

cursor.executemany

.executemany ( operation , seq_of_parameters )

Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters .

因此,如果您只针对 一个 组值执行查询,请这样称呼它:

values = ['val1', 'val2', 'val3']
cursor.executemany("INSERT INTO table (a, b, c) VALUES (?,?,?)", [values])

或者,对于多组值:

values1 = ['val1', 'val2', 'val3']
values2 = ['val3', 'val2', 'val1']
cursor.executemany("INSERT INTO table (a, b, c) VALUES (?,?,?)", [values1, values2])