我正在运行以下代码,这给了我一个错误
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 上执行时返回结果。你知道为什么这可能会失败吗?