MySQLdb : double quotes passed to the query
-
13-12-2019 - |
Question
I'm getting mad with MySQLdb ! I'm following exactly the official doc but I have an error with the code :
DB_TABLE = "test"
cursor.execute("SELECT MAX(id) AS maxid FROM " + DB_TABLE)
print "***"
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , (DB_TABLE,))
I get the error :
Traceback (most recent call last):
File "dbscript.py", line 49, in <module>
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , (DB_TABLE,))
File "build/bdist.macosx-10.7-intel/egg/MySQLdb/cursors.py", line 174, in execute
File "build/bdist.macosx-10.7-intel/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_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 ''test'' at line 1")
Obviously there is a problem with some quotes. My command seems to send a line like this to MySQL :
SELECT MAX(id) AS maxid FROM ''test''
How can I change the double quote by a single one ?
I'v tried the followings :
DB_TABLE = 'test'
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , [DB_TABLE])
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",))
But nothing works :(
Solution
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",))
and in similar statements, the cursor.execute
will substitute SQL parameters into %s.
What you need is something like this
sql = "SELECT MAX(id) AS maxid FROM %s" % ("test", )
cursor.execute(sql)
OTHER TIPS
You cannot parameterized table name, so you have to sanitize it yourself and use string substitution in the query instead.
To sanitize a table name in a query with multiple parameters:
query = "SELECT * FROM %s WHERE columnName = %s" % (tableName,'%s')
print(query)
At this point, query will display as:
SELECT * FROM tableName WHERE columName = %s
Once you've constructed your cursor, use the parameterized condition:
cursor.execute(query,(columnValue,))
The actual query that mySQL will read in then is:
SELECT * FROM tableName WHERE columnName = columnValue
If you try to pass in a table name without sanitizing it, you'll get a syntax error.