简体   繁体   中英

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM