python - MySQLdb : double quotes passed to the query

标签 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",))

但没有任何作用:(

最佳答案

你不能参数化表名,所以你必须自己清理它并在查询中使用字符串替换。

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

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/

相关文章:

Python MySQLdb 无法连接到服务器,SSL 问题

python - 比较两个数据库并找到连续的共同值

python - 在 python 中使用 MysqlDb 将 null 转换为 None

python - Pandas 时间序列事件之间的时间

python - HadoopStreaming R作为 reducer 失败

python 请求非 ascii 数据的问题

mySQL 返回每个字段的特定行

MySql 在 Windows 上运行但无法使用命令行连接

c++ - 如何使用 SOCI C++ Database 库?

python - 如何判断一个字符串是不是base64