在 SQL 查询中使用 Python 列表获取列名 [英] Use Python list in SQL query for column names

查看:82
本文介绍了在 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.

这篇关于在 SQL 查询中使用 Python 列表获取列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆