Python SQL 语句 拼接 in 查询

想要实现这样的查询语句:

select * from server where id=1 and ip in ('1.1.1.1','2.2.2.2','2.2.2.2')

我们希望在查询语句的 in 中放入一个 IP 列表,这里我们首先会想到的是用 join 来对这个列表处理成一个字符串,如下:

>>> a=['1.1.1.1','2.2.2.2','2.2.2.2']
>>> ','.join(a)
'1.1.1.1,2.2.2.2,2.2.2.2'

可以看到,join 后的结果并不是我们想要的结果,因为引号的问题。所以我们会想到另外的办法:

>>> sql_str = "select * from server where id=%s and ip in (%s)"
>>> a = ['1.1.1.1','2.2.2.2','2.2.2.2']
>>> ','.join(["'%s'" % item for item in a])
"'1.1.1.1','2.2.2.2','2.2.2.2'"
>>> ips = ', '.join(list(map(lambda item: "'%s'" % item, a)))
"'1.1.1.1', '2.2.2.2', '2.2.2.2'"
>>> sql_str % ('1', ips)
"select * from server where id=1 and ip in ('1.1.1.1', '2.2.2.2', '2.2.2.2')"
>>> cursor.execute(sql_str % ('1', ips))

另一种方式,如下:

>>> a = ['1.1.1.1','2.2.2.2','3.3.3.3']
>>> sql_str = 'select * from server where id=%s and ip in (%s)' % ('%s', ','.join(['%s'] * len(a)))
>>> sql_str
'select * from server where id=%s and ip in (%s,%s,%s)'
>>> cursor.execute(sql_str,['1', ] + a))

https://www.jianshu.com/p/2eaabb5c797d
https://blog.csdn.net/u011085172/article/details/79044490


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com

文章标题:Python SQL 语句 拼接 in 查询

文章字数:423

本文作者:Bin

发布时间:2019-01-02, 17:49:32

最后更新:2019-08-06, 00:07:35

原始链接:http://coolview.github.io/2019/01/02/Python/Python%20SQL%20%E8%AF%AD%E5%8F%A5%20%E6%8B%BC%E6%8E%A5%20in%20%E6%9F%A5%E8%AF%A2/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录