在 SQL 查询中使用 Python 列表获取列名

问题描述:

我在 Python 列表中有一堆列名.现在我需要使用该列表作为 SELECT 语句中的列名.我该怎么做?

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;

到目前为止我有:

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

cur.execute(sql,(pythonlist,name))

您不能将要选择的列列表作为参数传递给 cur.execute.它应该是您的 SQL 表达式的一部分,例如:

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

需要注意的一件事是 SQL 中参数值的占位符取决于数据库.如果 %s 不起作用,请尝试使用 ?:1.请参阅 https://www.python.org/dev/peps/pep-0249/#paramstyle 了解更多详情.

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.