繁体   English   中英

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说:

如果 args 是列表或元组,则%s可用作查询中的占位符。 如果 args 是字典,则%(name)s可以用作查询中的占位符。

即使:name占位符格式在您引用的 PEP 中,pymysql package 似乎也没有实现该格式。

这应该有效:

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"})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM