[英]Use Python list in SQL query for column names
I have a bunch of column names in a Python list. 我在Python列表中有一堆列名。 Now I need to use that list as the column names in a SELECT
statement. 现在,我需要将该列表用作SELECT
语句中的列名称。 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
. 您不能传递要选择为cur.execute
的参数的列列表。 It should be part of your SQL expression, something like: 它应该是您的SQL表达式的一部分,例如:
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. 要注意的一件事是,SQL中参数值的占位符取决于数据库。 If %s
doesn't work try using ?
如果%s
不起作用,请尝试使用?
or :1
. 或:1
。 See https://www.python.org/dev/peps/pep-0249/#paramstyle for more details. 有关更多详细信息,请参见https://www.python.org/dev/peps/pep-0249/#paramstyle 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.