0

So I am trying to pass months as a tuple to a sql query in python as below:

no_of_months = 6
months = tuple(months_list[no_of_months:])
months
Out[14]: ('201708', '201709', '201710', '201711', '201712', '201801')
wrk_hours = str("""select * from dbo.month_step where month_id IN \
 %s and tier = 'Sil';""") %months

However this throws an error as below:

TypeError: not all arguments converted during string formatting

Can someone please help me resolve this?

In case the months_list is needed:

['201702',
 '201703',
 '201704',
 '201705',
 '201706',
 '201707',
 '201708',
 '201709',
 '201710',
 '201711',
 '201712',
 '201801']
asked Feb 27, 2018 at 6:47

3 Answers 3

1

Try this:

wrk_hours = str("""select * from dbo.month_step where month_id IN %s and tier = 'Optimum Silver';""") %[x for x in months]
wrk_hours
Out[1]: "select * from dbo.month_step where month_id IN 
 ['201708', '201709', '201710', '201711', '201712', '201801'] and tier = 'Optimum Silver';"
answered Feb 27, 2018 at 6:57
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

wkr_hours = str("""select * from dbo.month_step where mont_id in \
(%s) and tier = 'Sil';""")%(",".join(map(lambda x:"'"+x+"'",months_list[no_of_months:])))
Shuvayan Das
1,0485 gold badges23 silver badges43 bronze badges
answered Feb 27, 2018 at 6:54

Comments

1

I think this should the trick:-

list_args = ['201708', '201709', '201710', 
'201711', '201712', '201801'] 
str("""select * from dbo.month_step where month_id IN (%s) and tier = 
'Sil';""") % (','.join(list_args))

It is simpler and works.

answered Feb 27, 2018 at 7:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.