简单查询上的 Python MySQL 语法错误

use*_*938 1 python mysql

我正在为 python 3.x 使用 MySQL 连接器,并且使用简单的代码遇到了这个问题,例如:

rest_cursor.execute("SELECT * FROM restaurant WHERE r_id=%s",(r_id))

其中 r_id 是一个整数。这导致抛出异常: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 '%s' at line 1

这种格式似乎与 python-MySQL 示例页面中的示例相匹配:http : //dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html

我究竟做错了什么?谢谢

Kla*_* D. 7

要创建单项元组,您必须在右括号前包含一个逗号:

rest_cursor.execute("SELECT * FROM restaurant WHERE r_id=%s", (r_id,))
Run Code Online (Sandbox Code Playgroud)

否则 Python 认为您只是为了分组而将值括在括号中。

再举一个例子,请注意 Python 计算这两个值的方式的不同:

(1) ? 1
(1,) ? (1,)
Run Code Online (Sandbox Code Playgroud)