python小技巧-sql语句IN在python中的格式化

例如sql语句可能是:

sql='''select
*
from
test_table
where 1
and id_no IN ({0})
'''

需要在python之中对sql进行格式化,先有id_no_list:

id_no_list=['123','456','678','111',]

对sql进行格式化:

def generate_string(id_no_list):
    test_string="','".join(id_no_list)
    test_string="'"+test_string+"'"
    return test_string

sql=sql.format(generate_string(id_no_list))
print(sql)

这样就可以处理sql中的in的格式化问题了,具体运行结果如下:

select
*
from
test_table
where 1
and id_no IN ('123','456','678','111')

 

posted @ 2023-11-15 19:15  stone9693  阅读(324)  评论(0)    收藏  举报
GitHub账户:https://github.com/stone9693