1

我正在构建一个查询字符串。

query = "SELECT seqid, date, name, steamid, team, text, type, '%s' as triggerword, '%s' as weight FROM chatlogs WHERE date > '%s' AND text LIKE '%%%s%%' ORDER BY DATE" % (word, weight, self.setting['LAST_RUN_TIME'], word)

如果我打印字符串,它会正确返回:

SELECT seqid, date, name, steamid, team, text, type, 'hunting_term' as triggerword, '0.01' as weight FROM chatlogs WHERE date > '2012-04-18 23:47:58.439124' AND text LIKE '%hunting_term%' ORDER BY DATE

但是,它会因 TypeError 异常而失败:TypeError: not enough arguments for format string

完整代码:

import database

mysqldb = database.Connection('localhost','mydb',user='myuser',password='mypass')

word = 'hunting_term'
weight = 0.01
setting = dict({'LAST_RUN_TIME':'2012-04-18 23:47:58.439124'})

query = "SELECT seqid, date, name, steamid, team, text, type, '%s' as triggerword, '%s' as weight FROM chatlogs WHERE date > '%s' AND text LIKE '%%%s%%' ORDER BY DATE" % (word, weight, setting['LAST_RUN_TIME'], word)
print query

for message in mysqldb.query(query):        # This is the line it throws the exception on
    print "A row"

数据库来自tornado

4

1 回答 1

6

这里的问题是对 MySQLdb 的最终调用看起来像这样:

query = "SELECT seqid, date, name, steamid, team, text, type, 'hunting_term' as triggerword, '0.01' as weight FROM chatlogs WHERE date > '2012-04-18 23:47:58.439124' AND text LIKE '%hunting_term%' ORDER BY DATE"
db.cursor().execute(query, ())

第一个参数db.cursor().execute()应该是格式字符串,第二个参数应该是该格式字符串的替换,您可以在MySQLdb 文档中看到这一点。换句话说,它将执行以下代码:

query % ()

如您所见,这将导致相同的 TypeError:

>>> query % ()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

这意味着%您希望 MySQL 看到的任何文字%%在被 看到时都必须是 a db.cursor().execute(),因此您应该能够通过将原始格式字符串更改为以下内容来解决此问题:

query = "SELECT seqid, date, name, steamid, team, text, type, '%s' as triggerword, '%s' as weight FROM chatlogs WHERE date > '%s' AND text LIKE '%%%%%s%%%%' ORDER BY DATE" % (word, weight, self.setting['LAST_RUN_TIME'], word)

然而,正确的做法是让 MySQLdb 为您执行替换,这会将您的代码更改为以下内容:

query = "SELECT seqid, date, name, steamid, team, text, type, %s as triggerword, %s as weight FROM chatlogs WHERE date > %s AND text LIKE %s ORDER BY DATE"
parameters = (word, weight, setting['LAST_RUN_TIME'], '%%%s%%' % word)
for message in mysqldb.query(query, *parameters):
    print "A row"
于 2012-04-19T17:36:54.907 回答