构建查询字符串时的Python TypeError

时间:2012-04-19 17:03:31

标签: python typeerror

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

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:格式字符串

的参数不足

完整代码:

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

1 个答案:

答案 0 :(得分: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 docs中看到这一点。换句话说,它将执行以下代码:

query % ()

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

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

这意味着当%看到你希望MySQL看到的任何文字%%都需要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"