2012-02-22 25 views
0

我的代碼:python和mysqldb:完美查詢語法錯誤?

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的它運行得很好。

我在忽略什麼?

+0

它用%s代替%% s,所以它可以在db.execute中使用,它將用idKey代替它 – 2012-02-22 12:46:44

回答

3

你應該看看更接近:

語法在''SELECT * FROM table WHERE person_oid = 16 order by RAND()limit 10',)'at line 1「)

而且您將在查詢的開始處看到雙撇號,並在末尾看到,)'

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

你已經在第一行的末尾有一個逗號,使其成爲一個元組

刪除它,您將不再需要在第二行。

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