是mysql.连接器报告不正确的参数样式?[mysql-connector-python 8.0.29]



使用mysql-connector-python 8.0.29mysql.connector.paramstyle报告'pyformat'

假设我已经正确理解了这里的文档https://peps.python.org/pep-0249/#paramstyle,下面应该是一个有效的SQL插入,当传递给execute()时-假设表存在,它确实存在-并通过参数['Python', 10]调用:

INSERT INTO lang(name, score) VALUES (%(c1)s, %(c2)s)

但是,当执行该命令时,返回以下错误:

mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

这强烈暗示格式%(<name>)s没有被解释为值占位符。

但是,如果我将插入更改为以下内容并像之前一样调用,则插入成功。

INSERT INTO lang(name, score) VALUES (%s, %s)

根据文档,%s是paramstyle 'format'而不是'pyformat'。

那么mysql.connector.paramstyle错误报告支持的样式吗?如果不是,我错过了什么?

背景:我正在将内部SQL库从Java移植到Python。由于它是一个库,它应该与RDBMS供应商保持中立,因此需要根据报告的paramstyle为PEP 249允许的所有格式生成适当的更新和查询。

# paramstyle.py
import mysql.connector
conf = {
'user': 'root',
'password': 'password',
'host': 'localhost',
'port': 3306,
'database': 'test'
}
c = mysql.connector.connect(**conf)
with c.cursor() as csr:
csr.execute('DROP TABLE IF EXISTS lang')
csr.execute('CREATE TABLE lang(name VARCHAR(50), score INTEGER)')
csr.execute('INSERT INTO lang(name, score) VALUES (%(c1)s, %(c2)s)',
['Python', 10])
#csr.execute('INSERT INTO lang(name, score) VALUES (%s, %s)',)
#    ['Python', 10])
c.commit()
c.close()

$ python3 paramstyle.py
Traceback (most recent call last):
File "paramstyle.py", line 13, in <module>
csr.execute('INSERT INTO lang(name, score) VALUES (%(c1)s, %(c2)s)',
File "/usr/local/lib/python3.8/site-packages/mysql/connector/cursor.py", line 559, in execute
raise errors.ProgrammingError(
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement

题外话:为什么PEP 249允许这五种不同的方法作为参数占位符?难道一个就足够了吗?这不会使需要独立于连接器的客户机代码复杂化吗?

pyformat并不意味着你必须使用%(name)s样式的参数。这意味着除了对有序参数使用 printf-style%s之外,还允许使用命名参数

但是要使用这些,您必须将参数放入字典中以关联名称。所以应该是:

csr.execute('INSERT INTO lang(name, score) VALUES (%(name)s, %(score)s)',
{'name': 'Python', 'score': 10])

最新更新