Skip to main content
 首页 » 编程设计

构建查询字符串时出现 Python TypeError

2025年05月04日25over140

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

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 异常而失败: 类型错误:格式字符串的参数不足

完整代码:

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包裹

请您参考如下方法:

这里的问题是对 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 

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

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"