MySQLdb:传递给查询的双引号

时间:2012-03-13 14:23:58

标签: python mysql mysql-python

我对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",))

但没有任何作用:(

2 个答案:

答案 0 :(得分:4)

cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",)) 

在类似的语句中,cursor.execute将SQL参数替换为%s。

你需要的是这样的东西

sql = "SELECT MAX(id) AS maxid FROM %s" % ("test", )
cursor.execute(sql)

答案 1 :(得分:4)

您无法参数化表名,因此您必须自己清理它并在查询中使用字符串替换。

在具有多个参数的查询中清理表名:

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

如果您尝试传入表名而不对其进行清理,则会出现语法错误。