我知道sqlite3有
data = {'test_col': 012345679}
sqlite3_conn.execute("""
UPDATE test_db SET test_col = :test_col
;""", data)
并且 mysql-connector-python 有
data = {'test_col': 012345679}
mysql_conn.execute("""
UPDATE test_db SET test_col = %(test_col)s
;""", data)
但是 pyodbc 支持任何形式的命名参数吗?我喜欢能够将
dict
传递给执行方法。非常方便,而且对于我的一些疑问,比如INSERT INTO ... ON DUPLICATE KEY UPDATE
,是需要的。
它不支持命名参数,但以正确顺序传递的绑定参数相当简单:
x = "This"
y = 345
mssql_cur.execute("SELECT * FROM mytable WHERE colx = ? AND coly = ?", x, y)
或
mssql_cur.execute("SELECT * FROM mytable WHERE colx = ? AND coly = ?", (x, y))
此处有更多详细信息和选项,例如传递
executemany
参数:
https://github.com/mkleehammer/pyodbc/wiki/Cursor
祝你好运!
您可以创建一个辅助函数,将仅接受位置参数的
execute
方法转换为接受命名参数的包装函数。使用正则表达式模式来获取冒号后的名称,但忽略带引号的字符串和注释:
import re
def to_positional(func, _pattern=re.compile(r"'(?:''|[^'])*'|--.*|:(\w+)")):
def execute(operation, namespace):
def replacer(match):
if name := match[1]:
params.append(namespace[name])
return '?'
return match[0]
params = []
return func(_pattern.sub(replacer, operation), params)
return execute
这样您就可以使用带有命名参数的查询来调用包装的
execute
方法:
sql = """\
UPDATE products
SET
name=:name,
price=:price,
description=':description ''' || :description || ''''
WHERE id=:id; -- :comment
"""
data = {'id': 123, 'name': 'foo', 'price': 99.99, 'description': 'foo description'}
to_positional(mssql_cur.execute)(sql, data)
为了更轻松地查看转换后的查询而不涉及数据库,您可以使辅助函数换行
print
而不是 mssql_cur.execute
:
to_positional(print)(sql, data)
所以它会输出:
UPDATE products
SET
name=?,
price=?,
description=':description ''' || ? || ''''
WHERE id=?; -- :comment
['foo', 99.99, 'foo description', 123]