python和mysqldb:完美的查询语法错误?

时间:2012-02-22 12:42:31

标签: python mysql-python

我的代码:

selectQ ="""SELECT * FROM  %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit),
self.db.execute(str(selectQ),(idKey))

我得到这个例外: mysql_exceptions.ProgrammingError: (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 ''SELECT * FROM table WHERE person_oid = 16 order by RAND() limit 10',)' at line 1")

但是,如果我复制查询并通过mysql运行它运行就好了。

我在俯瞰什么?

2 个答案:

答案 0 :(得分:3)

你应该仔细观察:

  

语法使用'' SELECT * FROM表WHERE person_oid = 16 order   由兰德()限制10',)'在第1行")

您会在查询开头看到双撇号,并在结尾处看到,)'

selectQ ="""SELECT * FROM  %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit),
self.db.execute(str(selectQ),(idKey))

你在第一行的末尾有一个逗号,使其成为一个元组

删除它,第二行不需要str(selectQ)

答案 1 :(得分:2)

你在第一行(结尾)有一个逗号:

selectQ ="""SELECT * FROM  %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit),
self.db.execute(str(selectQ),(idKey))

将其更改为:

selectQ ="""SELECT * FROM  %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit)
self.db.execute(str(selectQ),(idKey))