1064:执行 PyMySQL 查询的 SQL 语法错误 [英] 1064: SQL syntax error executing PyMySQL query

查看:178
本文介绍了1064:执行 PyMySQL 查询的 SQL 语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>pymysql.paramstyle格式

我的db和cursor详情如下:

<预><代码>>>>MYDB = pymysql.connect(_params_)>>>游标 = MYDB.cursor()

然后我使用,

执行 SQL 查询<预><代码>>>>cursor.execute("SELECT * FROM %(tablename)s", {"tablename": "activity"})

我收到一个错误说明,

ProgrammingError: (1064, u"You have an error in your SQL syntax; 检查与您的 MySQL 服务器版本相对应的手册以了解在第 1 行的 '''activity''' 附近使用正确的语法")

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

<预><代码>>>>unsafe_sql = ("从活动中选择 *")>>>cursor.execute(unsafe_sql)>>>4

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

解决方案

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

cursor.execute("SELECT * FROM %(tablename)s" % {"tablename": "activity"})

I am using PyMySQL to execute SQL query commands from python. My pystyle is pyformat which was found using:

>>> pymysql.paramstyle
pyformat

My db and cursor details are as follows:

>>> MYDB = pymysql.connect(_params_)
>>> cursor = MYDB.cursor()

I then execute a SQL query using,

>>> cursor.execute("SELECT * FROM %(tablename)s",  {"tablename": "activity"})

I get an error stating,

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

On the other hand, the query by itself works,

>>> unsafe_sql = ("Select * from activity")
>>> cursor.execute(unsafe_sql)
>>> 4

I am not sure what is going on with my first query. Any help appreciated.

解决方案

You can't pass a table name as a parameter to cursor.execute(). Whenever a parameter is a string it quotes it when it substitutes into the query. Use a normal string formatting method, e.g.

cursor.execute("SELECT * FROM %(tablename)s" % {"tablename": "activity"})

这篇关于1064:执行 PyMySQL 查询的 SQL 语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆