猿问

在 sql 查询 python 中使用时,格式选项不起作用

我必须.format使用python. 我正在使用以下代码,但它不能按预期工作。


alarm_tables = ["treevashialarm","treekhopolialarm","treetalegaonalarm"]

alarm_types = ['As%%','Sd%%','Multi%%']

这是我的查询:


query_types = "SELECT \"alarmSeverity\", COUNT(*) FROM " + "'{0}'" + " WHERE isparent = true and eventdate+eventtime BETWEEN TIMESTAMP " + "'{1}" + "T18:30:00.000Z' " + " and TIMESTAMP " + "'{2}" + "T18:29:59.999Z' " + "and eventtype like '{3}' group by \"alarmSeverity\""

我正在使用如下格式选项:


for i in alarm_tables:

    for j in alarm_types:

        query_types.format(i,'2019-10-01','2019-10-02',j)

        print(query_types)

我得到如下输出:


SELECT "alarmSeverity", COUNT(*) FROM '{0}' WHERE isparent = true and eventdate+eventtime BETWEEN TIMESTAMP '{1}T18:30:00.000Z'  and TIMESTAMP '{2}T18:29:59.999Z' and eventtype like '{3}' group by "alarmSeverity"

我的预期输出之一如下:


SELECT "alarmSeverity", COUNT(*) FROM treevashialarm WHERE isparent = true and eventdate+eventtime BETWEEN TIMESTAMP '2019-10-09T18:30:00.000Z' AND TIMESTAMP '2019-10-10T18:29:59.999Z' and eventtype like 'As%' group by "alarmSeverity";

我怎样才能得到想要的。output为什么format不工作。是否有解决方法。也不工作。它在随机时间for loop给出。random output


任何帮助表示赞赏!


慕斯709654
浏览 88回答 1
1回答

烙印99

format()不修改原始字符串:所以如果你想这样做,你必须写:query_types_formated = query_types.format(i,'2019-10-01','2019-10-02',j)
随时随地看视频慕课网APP

相关分类

Python
我要回答