Reputation: 804
I have to write an sql query using the .format
option in python
. I am using the follwoing code which doesnt work as I expected.
alarm_tables = ["treevashialarm","treekhopolialarm","treetalegaonalarm"]
alarm_types = ['As%%','Sd%%','Multi%%']
Here is my query:
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\""
I am using the format option as below:
for i in alarm_tables:
for j in alarm_types:
query_types.format(i,'2019-10-01','2019-10-02',j)
print(query_types)
I am getting an output as below :
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"
My one of the Expected output is as below:
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";
How can I get the desired output
.Why is format
not working.Is there a work around.The for loop
doesnt work as well.It gives random output
at random time.
Any help is appreciated!
Upvotes: 0
Views: 362
Reputation: 858
format()
doesn't modify the original string:
so if you want to do this you have to write:
query_types_formated = query_types.format(i,'2019-10-01','2019-10-02',j)
Upvotes: 4