gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:52:43 24 4
gpt4 key购买 nike

当我想在 MySQL 的选择查询中传递其他变量时,使用 .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 错误。那么,正确的方法是什么?!

最佳答案

在你的情况下,

试试这个:

>>> 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()

关于python - 在 MySQL 的选择查询中传递其他变量时,使用 .format 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36970752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com