3

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`
4
  • Yes, this should be possible, at least in theory. What is your actual question? Commented Feb 18, 2019 at 6:11
  • 2
    ...although this kind of problem can be symptomatic of poorly designed databases/tables/columns Commented Feb 18, 2019 at 6:12
  • Yes its possible. For examples, Check out this python sqlite documentation. docs.python.org/2/library/sqlite3.html Commented Feb 18, 2019 at 6:20
  • Are you using MySQL or Postgresql? Commented Feb 18, 2019 at 7:13

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

Both methods worked great especially the first one, thank you!

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.