我对 MySQLdb 很生气!我完全按照官方文档进行操作,但代码有错误:
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,))
我得到错误:
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")
显然有些引号有问题。我的命令似乎向 MySQL 发送了这样一行:
SELECT MAX(id) AS maxid FROM ''test''
如何用一个单引号更改双引号?
我试过以下方法:
DB_TABLE = 'test'
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , [DB_TABLE])
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",))
但没有任何作用:(
最佳答案
你不能参数化表名,所以你必须自己清理它并在查询中使用字符串替换。
要清理具有多个参数的查询中的表名:
query = "SELECT * FROM %s WHERE columnName = %s" % (tableName,'%s')
print(query)
此时,查询将显示为:
SELECT * FROM tableName WHERE columName = %s
构建游标后,使用参数化条件:
cursor.execute(query,(columnValue,))
mySQL 将读入的实际查询是:
SELECT * FROM tableName WHERE columnName = columnValue
如果您尝试在不对其进行清理的情况下传入表名,则会出现语法错误。
关于python - MySQLdb : double quotes passed to the query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9685953/