1064:执行 PyMySQL 查询的 SQL 语法错误

lor*_*das 3 python mysql pymysql

我正在使用 PyMySQL 从 python 执行 SQL 查询命令。我的 pystyle 是pyformat使用以下方法找到的:

>>> pymysql.paramstyle
pyformat
Run Code Online (Sandbox Code Playgroud)

我的数据库和游标详细信息如下:

>>> MYDB = pymysql.connect(_params_)
>>> cursor = MYDB.cursor()
Run Code Online (Sandbox Code Playgroud)

然后我使用执行 SQL 查询,

>>> cursor.execute("SELECT * FROM %(tablename)s",  {"tablename": "activity"})
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说明,

ProgrammingError: (1064, u"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 '''activity''' at line 1")
Run Code Online (Sandbox Code Playgroud)

另一方面,查询本身有效,

>>> unsafe_sql = ("Select * from activity")
>>> cursor.execute(unsafe_sql)
>>> 4
Run Code Online (Sandbox Code Playgroud)

我不确定我的第一个查询发生了什么。任何帮助表示赞赏。

Bar*_*mar 5

您不能将表名作为参数传递给cursor.execute(). 每当参数是字符串时,它会在替换到查询中时引用它。使用普通的字符串格式化方法,例如

cursor.execute("SELECT * FROM %(tablename)s" % {"tablename": "activity"})
Run Code Online (Sandbox Code Playgroud)