python拼接 select in语句

拼接sql语句时,有时候参数是一个列表,想实现select in语句的效果,比如sql语句:select * from user where userid in (‘A’, ‘C’),但是只有列表参数args=[‘A’, ‘C’],首先尝试了如下方式:

"select * from user where userid in (%s)"  % (','.join(args))

发现会报错”Unknown column ‘A’ in ‘where clause”,原因是拼接出来的没有带引号。最后拼成了

select * from user where userid in (A, C)

最后解决方案是:

Python 3:

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
 in_p=', '.join(list(map(lambda x: "'%s'" % x, args)))
sql = sql % in_p
cursor.execute(sql, args)

Python 2:

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)' 
in_p=', '.join(map(lambda x: "'%s'" % x, args))
sql = sql % in_p
cursor.execute(sql, args)
    原文作者:leyu
    原文地址: https://www.jianshu.com/p/2eaabb5c797d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞