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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With