Python pymysql 库中如何绑定参数?
How do you bind parameters in the Python pymysql library?
如此处 https://peps.python.org/pep-0249/#paramstyle 所述,在 MySql 中应该可以使用关键字语法绑定参数,如下所示:email=:email
。这不同于使用未命名的占位符语法,例如 email=%s
.
但是这段代码不起作用:
import pymysql
con = pymysql.connect(host='localhost', user='root', password=pw, database=db_name, port=4306)
stmt = "INSERT INTO `test_table` (`email`, `password`) VALUES (:email, :password)"
with con.cursor() as cursor:
# Create a new record
cursor.execute(stmt, {'email': "FOO", 'password': "BAR"})
con.commit()
甚至没有添加
pymysql.paramstyle = 'named'
在顶部。
错误是
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':email, password=:password)' at line 1")
但不幸的是,我找不到这样的文档(此页面未记录任何内容.. https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html)
正确的语法是什么?
谢谢!
https://pymysql.readthedocs.io/en/latest/modules/cursors.html 说:
If args is a list or tuple, %s
can be used as a placeholder in the query. If args is a dict, %(name)s
can be used as a placeholder in the query.
尽管 :name
占位符格式在您引用的 PEP 中,但 pymysql 包似乎并未实现该格式。
这应该有效:
stmt = "INSERT INTO `test_table` (`email`, `password`) VALUES (%(email)s, %(password)s)"
with con.cursor() as cursor:
# Create a new record
cursor.execute(stmt, {'email': "FOO", 'password': "BAR"})
如此处 https://peps.python.org/pep-0249/#paramstyle 所述,在 MySql 中应该可以使用关键字语法绑定参数,如下所示:email=:email
。这不同于使用未命名的占位符语法,例如 email=%s
.
但是这段代码不起作用:
import pymysql
con = pymysql.connect(host='localhost', user='root', password=pw, database=db_name, port=4306)
stmt = "INSERT INTO `test_table` (`email`, `password`) VALUES (:email, :password)"
with con.cursor() as cursor:
# Create a new record
cursor.execute(stmt, {'email': "FOO", 'password': "BAR"})
con.commit()
甚至没有添加
pymysql.paramstyle = 'named'
在顶部。
错误是
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':email, password=:password)' at line 1")
但不幸的是,我找不到这样的文档(此页面未记录任何内容.. https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html)
正确的语法是什么?
谢谢!
https://pymysql.readthedocs.io/en/latest/modules/cursors.html 说:
If args is a list or tuple,
%s
can be used as a placeholder in the query. If args is a dict,%(name)s
can be used as a placeholder in the query.
尽管 :name
占位符格式在您引用的 PEP 中,但 pymysql 包似乎并未实现该格式。
这应该有效:
stmt = "INSERT INTO `test_table` (`email`, `password`) VALUES (%(email)s, %(password)s)"
with con.cursor() as cursor:
# Create a new record
cursor.execute(stmt, {'email': "FOO", 'password': "BAR"})