python拼接 select in语句

2017-01-16  本文已影响0人  leyu

拼接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)
上一篇下一篇

猜你喜欢

热点阅读