0

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!

1 Answer 1

4

format() doesn't modify the original string:

enter image description here

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that as well earlier,but for loop was not working :O weird eh? .Anyway now it works.Thanks a bunch! :)
@RAMSHANKERG I'm guessing you tried with query_types = query_types.format(...), so the first loop was okay but the second one broke because your query_types was not a formatable string anymore since you replaced it ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.