2020年11月4日 星期三

將python的list轉為讓sql where in可以使用 - sql where operator in python list

Code

'''
System version : Windows 10  64-bit  
Python version : Python 3.6.0 :: Anaconda 4.3.1 (64-bit)   
'''
id_list = ['a','b']
sql_id_list = str(tuple([key for key in id_list])).replace(',)', ')')
query ="""
    SELECT id FROM table WHERE article_id IN {sql_id_list}
""".format(sql_id_list=sql_id_list)
print("sql_id_list:",sql_id_list)
print("query:",query)

id_list = ['a']
sql_id_list = str(tuple([key for key in id_list])).replace(',)', ')')
query ="""
    SELECT id FROM table WHERE article_id IN {sql_id_list}
""".format(sql_id_list=sql_id_list)
print("sql_id_list:",sql_id_list)
print("query:",query)
# cursor.execute(execute_str,values)

Result

sql_id_list: ('a', 'b')
query:
    SELECT id FROM table WHERE article_id IN ('a', 'b')

sql_id_list: ('a')
query:
    SELECT id FROM table WHERE article_id IN ('a')

沒有留言:

張貼留言