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`
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With