my first question up here, please be kind. I am new to both python and SQL so I am finding my way. I am writing a function in python which should select columns from a table in the database with column names coming from a variable (list). Below is what I want the code to look like, obviously it does not work. Is there a way to do it, or I should not bother and instead of a list type column names directly into c.execute? Thank you! Alex
def data_extract1():
column_list1 = ["column1","column2"]
c.execute ('SELECT column_list1 FROM myBD' )
for row in c.fetchall():
print (row)
1 Answer 1
You can use format() and join() to replace column_list1 in your query string with the columns you want.
c.execute('SELECT {} FROM myBD'.format(", ".join(column_list1)))
", ".join(column_list1) creates a comma-separated string from your column list.
format() replaces the {} in your query string with that new string