Python 在MySQL的select查询中传递其他变量时,使用.format的正确方法是什么?

Python 在MySQL的select查询中传递其他变量时,使用.format的正确方法是什么?,python,mysql,Python,Mysql,当我想在MySQL的select查询中传递其他变量时,使用.format的正确方法是什么 例如,我有一个查询,我不知道如何正确地传递所有参数 a = "c9" # this is for %s b = "TEMP" # this is for the first {} c = "1 hour" # this is for the last {} c.execute("SELECT Client, {}, Date_Time from data where Client = %s and Date

当我想在MySQL的select查询中传递其他变量时,使用.format的正确方法是什么

例如,我有一个查询,我不知道如何正确地传递所有参数

a = "c9" # this is for %s
b = "TEMP" # this is for the first {}
c = "1 hour" # this is for the last {}
c.execute("SELECT Client, {}, Date_Time from data where Client = %s and Date_Time > DATE_SUB(NOW(), INTERVAL {}".format(b,a,c)) # This doesn't work 

我还尝试了许多其他的变体,但它们都不起作用,我仍然得到了
1064
错误。那么,正确的方法是什么

您想使用单一格式系统-
{}
是一种格式系统,而
%s
是较旧的格式系统

改变这个

c.execute("SELECT Client, {}, Date_Time from data where Client = %s and Date_Time > DATE_SUB(NOW(), INTERVAL {}".format(b,a,c)) # This doesn't work 

您还可以使用命名字段:

c.execute("SELECT Client, {field}, Date_Time from data where Client = {client} and Date_Time > DATE_SUB(NOW(), INTERVAL {interval}".format(
    field = b, client = a, interval = c))
但是,在查询中使用字符串插值(即格式化)并不总是最好的方法,因为可能会发生SQL注入攻击和其他利用漏洞的行为。您需要在将用户数据传递到查询之前对其进行清理——符合DB API的库应该为您完成这项工作。有关更具体的示例,请参见。

在您的案例中

  • 缺少右括号
  • 在和中混合使用
试试这个:

>>> a = "c9" # this is for %s
>>> b = "TEMP" # this is for the first {}
>>> c = "1 hour" # this is for the last {}
>>> sql = "SELECT Client, {}, Date_Time from data where Client = \"{}\" and Date_Time > DATE_SUB(NOW(), INTERVAL {})".format(b,a,c)
>>> sql
'SELECT Client, TEMP, Date_Time from data where Client = "c9" and Date_Time > DATE_SUB(NOW(), INTERVAL 1 hour)'
>>>
>>> cur = db.cursor()
>>> cur.execute(sql)  
>>> data = cur.fetchall()   
>>> cur.close()

1064错误是什么?您是否尝试将%s更改为{}@RUSHYPANCAL您错过了右括号
。它应该是
DATE\u SUB(NOW(),INTERVAL{}
)。详细描述请参考我的答案。谢谢先生。我先尝试了您的答案,但出现了错误1054:
where子句中未知的列“c9”
。另一个对我有用。谢谢你,先生。这就像一个老板。为什么我们需要第二个变量tho的
\“{}\”
Client={}
将是
Client=c9
。我想
c9
应该是一个字符串。但是等等,你错过了一个
=
<代码>客户端==“C9”?哦,现在我明白了。否否查询只需要在
=
上进行,因此
客户端=\“{}\”
实际上是正确的
>>> a = "c9" # this is for %s
>>> b = "TEMP" # this is for the first {}
>>> c = "1 hour" # this is for the last {}
>>> sql = "SELECT Client, {}, Date_Time from data where Client = \"{}\" and Date_Time > DATE_SUB(NOW(), INTERVAL {})".format(b,a,c)
>>> sql
'SELECT Client, TEMP, Date_Time from data where Client = "c9" and Date_Time > DATE_SUB(NOW(), INTERVAL 1 hour)'
>>>
>>> cur = db.cursor()
>>> cur.execute(sql)  
>>> data = cur.fetchall()   
>>> cur.close()