python and mysqldb: syntax error on perfectly good query ?
-
29-10-2019 - |
سؤال
My code:
selectQ ="""SELECT * FROM %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit),
self.db.execute(str(selectQ),(idKey))
I get this exception:
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")
However if I copy the query and run it through mysql it runs just fine.
What am I overlooking ?
المحلول
You should look closer to:
syntax to use near ''SELECT * FROM table WHERE person_oid = 16 order by RAND() limit 10',)' at line 1")
And you will see double apostrophe at the beginning of the query and ,)'
at the end of it.
selectQ ="""SELECT * FROM %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit),
self.db.execute(str(selectQ),(idKey))
You've got a comma at the end of the first line, making it a tuple
Remove it and you will not need str(selectQ)
on the second line.
نصائح أخرى
You have a comma to much in the first line (at the end):
selectQ ="""SELECT * FROM %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit),
self.db.execute(str(selectQ),(idKey))
Change it to:
selectQ ="""SELECT * FROM %s WHERE %s = %%s order by RAND() limit %s""" % (self.table,self.columnSpecName,limit)
self.db.execute(str(selectQ),(idKey))