Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Python list in SQL query for column names

I have a bunch of column names in a Python list. Now I need to use that list as the column names in a SELECT statement. How can I do that?

pythonlist = ['one', 'two', 'three']

SELECT pythonlist FROM data;

So far I have:

sql = '''SELECT  %s FROM data WHERE name = %s INTO OUTFILE filename'''

cur.execute(sql,(pythonlist,name))
like image 600
LK27 Avatar asked Feb 10 '23 01:02

LK27


1 Answers

You cannot pass list of columns to select as a parameter to cur.execute. It should be part of your SQL expression, something like:

sql = "SELECT " + ",".join(pythonlist) + " FROM data WHERE name = %s INTO OUTFILE filename"
cur.execute(sql, (name,))

One thing to be aware of is that placeholder for a parameter value in the SQL depends on the database. If %s doesn't work try using ? or :1. See https://www.python.org/dev/peps/pep-0249/#paramstyle for more details.

like image 100
kostya Avatar answered Feb 12 '23 14:02

kostya