0

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

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 上执行时返回结果。你知道为什么这可能会失败吗?

4

1 回答 1

2

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

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

... LIKE %s ORDER BY id

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

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

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

然后做一些与查询完全不同的事情:

cursor.execute("... %s", ('spam',))
于 2013-04-11T22:32:37.043 回答