5

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))
LK27
  • 53
  • 1
  • 6

1 Answers1

9

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.

kostya
  • 9,221
  • 1
  • 29
  • 36
  • I didn't know that `(name)` is different from `(name,)`. The additional comma makes it a tuple which execute needs. Thanks. – NeoJi Sep 02 '16 at 14:24