在python中将列表传递给sql

Dat*_*ast 3 python sql list

我正在尝试将列表传递给 sql。根据我的发现,bind列表没有类型。因此,我尝试将列表转换为字符串:这是我尝试执行的 sql:

select a,b,sum(c) as total from t where d in ('x','y') group by 1,2
Run Code Online (Sandbox Code Playgroud)

由于我必须对其进行参数化,因此我使用了以下内容:

import pandas as pd
import pyodbc
#conn_vertica -- connection object to vertica
f_list = ['x','y']
sql_test=   select a,b,sum(c) as total from t where d in (%s) group by 1,2
l = ', '.join(map(lambda x: '%s',f_list))
sql_test = sql_test % l
df_test = pd.read_sql(sql_test,conn_vertica) # to read it into a dataframe
Run Code Online (Sandbox Code Playgroud)

在运行这个我得到一个错误:

pandas.io.sql.DatabaseError: Execution failed on sql 'select a, b, sum(c) as total from t where d in (%s, %s)  group by 1,2': ('42601', '[42601] ERROR 4856:  Syntax error at or near "%" at character 123\n (4856) (SQLExecDirectW)')
Run Code Online (Sandbox Code Playgroud)

关于如何将列表传递到 sql 的任何建议

Ale*_*der 5

您可以将其作为元组传递:

sql_test = "SELECT a, b, SUM(c) AS total FROM t WHERE d IN {0} GROUP BY 1, 2".format(tuple(f_list))

>>> sql_test
"SELECT a, b, SUM(c) AS total FROM t WHERE d IN ('x', 'y') GROUP BY 1, 2"
Run Code Online (Sandbox Code Playgroud)