Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding SQL Queries in For Loop in Python

Is there a way to add SQL queries in a For Loop in python where the table names and database names are variable? Something like this:

database = []
tables= []
column = []

for x in database: 
    for y in tables:
        for z in column:
            SQL = "select * from x.y where z is NOT NULL;"
            cursor.execute(sql)`enter code here`
like image 207
Jaideep Chauhan Avatar asked May 14 '26 03:05

Jaideep Chauhan


2 Answers

Just use string formatting. In your example:

database = []
tables= []
column = []

for x in database: 
    for y in tables:
        for z in column:
            SQL = "select * from {x}.{y} where {z} is NOT NULL;".format(x=x, y=y, z=z)
            cursor.execute(sql)

It's a single example of python string formatting, but you either can use string concatenation, % formatting or f-strings.

like image 97
Lich Avatar answered May 16 '26 16:05

Lich


Just use .format() method of string object to get the sql query string:

SQL = "select * from {}.{} where {} is NOT NULL;".format(x, y, z)

Or append values like this:

SQL = "select * from " + str(x) + "." + str(y) + " where " + str(z) + " is NOT NULL;"

I recommend the first solution.

like image 34
Novak Avatar answered May 16 '26 17:05

Novak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!