Skip to content
Advertisement

Python – Passing list of fields as column to SQL query

I am trying to pass a list of columns into a SQL query in Python. This just returns back the list but not the actual columns as shown:

cols = ["col_a","col_b","col_c"]


query = f"""select '{cols}' from table"""


Current Output : f"""select '["col_a","col_b","col_c"]' from table"""

Expected output: f"""select col_a, col_b, col_c from table"""

Advertisement

Answer

You want to do a join of the list:

query = f"""select {", ".join(cols)} from table"""
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement