当引用添加到参数时,Python MySQLdb查询返回错误

时间:2013-04-11 21:15:10

标签: python mysql

我正在运行以下代码,这给了我一个错误

import MySQLdb as mdb

source_sentence = "%Barack Obama%"
filterquery = ""
try:
    con = mdb.connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB)
    cur = con.cursor()

    print "SELECT sentence_id FROM translation_all WHERE source_sentence LIKE '%s' %s ORDER BY id" % (source_sentence, filterquery)
    cur.execute("SELECT sentence_id FROM translation_all WHERE source_sentence LIKE '%s' %s ORDER BY id", (source_sentence, filterquery))

    uid = cur.fetchone()
    print uid
except mdb.Error, e:
    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
finally:    
    if con:    
        con.close()

错误如下:

SELECT sentence_id FROM translation_all WHERE source_sentence LIKE '%Barack Obama%'  ORDER BY id
Error 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 '%Barack Obama%'' '' ORDER BY id' at line 1

如果我在查询中用双引号替换单引号,则没有错误,但是给出了空查询

SELECT sentence_id FROM translation_all WHERE source_sentence LIKE "%Barack Obama%"  ORDER BY id
None

有趣的是,上面的两个查询都可以通过命令行或phpmyadmin直接在mysql上执行返回结果。你知道为什么会失败吗?

1 个答案:

答案 0 :(得分:2)

当您将参数传递给cur.execute时,dbapi已经为您进行了引用。这意味着不要使用:

... LIKE '%s' %s ORDER BY id

... LIKE %s ORDER BY id

你会注意到我删除了第二个%s因为这里有错误。当它被''替换时,查询没有意义。

不要让自己被执行查询之前打印的字符串所迷惑。这不是执行的查询:

"... %s" % ('spam',)

与查询完全不同的是:

cursor.execute("... %s", ('spam',))