I have a list of integers that contains EMPI_ID
JavaScript
x
2
1
emp_list = [1,2]
2
I have a variable that defines the SQL query
JavaScript
1
8
1
emp_sql = '''
2
select
3
emp_id
4
, emp_name
5
from emp
6
where emp in (%s)
7
'''
8
Columns for the dataframe:
JavaScript
1
2
1
emp_columns = [emp_id, emp_name]
2
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.
JavaScript
1
5
1
emp = ','.join(emp_list)
2
sql_string = emp_sql%(emp)
3
data = connection.fetchall(sql_string)
4
df = pd.DataFrame.from_records(data, columns=emp_columns)
5
Please advise how i can change the query to substitute the IN clause of SQL with list of integers. from_records does not have param as parameter to pass the joined sql string.
Advertisement
Answer
list comprehension is you friend
JavaScript
1
10
10
1
emp_sql = f'''
2
select
3
emp_id
4
, emp_name
5
from emp
6
where emp in (%s)
7
'''%(", ".join([str(i) for i in emp_list]))
8
9
print(emp_sql)
10
output:
JavaScript
1
6
1
select
2
emp_id
3
, emp_name
4
from emp
5
where emp in (1, 2)
6
join only works with str
, so you have to convert the elements in the list, thats where you can use list comprehension. With the join, you can enter them into the query.
EDIT: if you want the numbers quoted, try this
JavaScript
1
10
10
1
emp_sql = f'''
2
select
3
emp_id
4
, emp_name
5
from emp
6
where emp in (%s)
7
'''%(", ".join([f"'{i}'" for i in emp_list]))
8
9
print(emp_sql)
10
giving this output:
JavaScript
1
6
1
select
2
emp_id
3
, emp_name
4
from emp
5
where emp in ('1', '2')
6