[英]Converting list to comma separated integers to be substituted in IN clause of Pandas dataframe query
I have a list of integers that contains EMPI_ID我有一个包含 EMPI_ID 的整数列表
emp_list = [1,2]
I have a variable that defines the SQL query我有一个定义 SQL 查询的变量
emp_sql = '''
select
emp_id
, emp_name
from emp
where emp in (%s)
'''
Columns for the dataframe: dataframe 的列:
emp_columns = [emp_id, emp_name]
When I try to convert them to comma separated integer values, the sql_string hold Str values and is failing to fetch the data from database.当我尝试将它们转换为逗号分隔的 integer 值时,sql_string 保存 Str 值并且无法从数据库中获取数据。
emp = ','.join(emp_list)
sql_string = emp_sql%(emp)
data = connection.fetchall(sql_string)
df = pd.DataFrame.from_records(data, columns=emp_columns)
Please advise how i can change the query to substitute the IN clause of SQL with list of integers.请告知我如何更改查询以用整数列表替换 SQL 的 IN 子句。 from_records does not have param as parameter to pass the joined sql string.
from_records 没有参数作为参数来传递连接的 sql 字符串。
list comprehension is you friend列表理解是你的朋友
emp_sql = f'''
select
emp_id
, emp_name
from emp
where emp in (%s)
'''%(", ".join([str(i) for i in emp_list]))
print(emp_sql)
output: output:
select
emp_id
, emp_name
from emp
where emp in (1, 2)
join only works with str
, so you have to convert the elements in the list, thats where you can use list comprehension. join 仅适用于
str
,因此您必须转换列表中的元素,这就是您可以使用列表理解的地方。 With the join, you can enter them into the query.通过联接,您可以将它们输入到查询中。
EDIT: if you want the numbers quoted, try this编辑:如果你想要引用的数字,试试这个
emp_sql = f'''
select
emp_id
, emp_name
from emp
where emp in (%s)
'''%(", ".join([f"'{i}'" for i in emp_list]))
print(emp_sql)
giving this output:给出这个 output:
select
emp_id
, emp_name
from emp
where emp in ('1', '2')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.