1

Is there a way to add SQL queries in a For Loop in python when i have two variable for each iteration? i have two list, and each member of the list corresponds to another member of the list in the order in which they are in the list. Example:

list1 = ['727', '454', '565']

list2 = ['14','15','16']

my_query= '''
    select 
    my rows
    from my_table
    where field1 = var_from_list1 
    and field2 = var_from_list2
) '''

So there we have possible pairs for vars {'727', 14'}, {'454', '15'}, {'565','16'} I want to make loop, which will take the variables from the list, insert them into the query, and then append results into pandas dataframe. I tried several options, but they did not work for me. I suppose that first need to create a dataframe with the necessary fields, and then append loop results into it, but idk how to correctly transfer the variables inside the request.

1 Answers1

0

You can add your real query around them, and then execute:

list1 = ['727', '454', '565']
list2 = ['14', '15', '16']

for l1, l2 in zip(list1, list2):
    print("select my_rows from my_table where field1=%s and field2=%s" % (l1, l2))

Output:

select my_rows from my_table where field1=727 and field2=14
select my_rows from my_table where field1=454 and field2=15
select my_rows from my_table where field1=565 and field2=16

Related Python doc is here.


To create data frame with necessary fields, you can check this post: Python Pandas Data frame creation


To insert row to dataframe please check: Insert a row to pandas dataframe

Sercan
  • 2,081
  • 2
  • 10
  • 23