mysqldb:传递给查询的双引号
-
13-12-2019 - |
题
我很生气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''
.
如何通过单个换一个单引号?
i'v尝试了以下内容:
DB_TABLE = 'test'
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , [DB_TABLE])
cursor.execute("SELECT MAX(id) AS maxid FROM %s" , ("test",))
.
但没有工作:(
解决方案
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)
. 其他提示
您无法参数化表名,因此您必须自己清理它并在查询中使用字符串替换。
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
.
如果您尝试在未经消毒的情况下传递表名,则会获得语法错误。
不隶属于 StackOverflow