python mysql where in 对列表(list,,array)问题

2023年1月21日11:57:22

例如有这么一个查询语句:

select * from server where ip in (....)

同时一个存放ip 的列表 :['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后的结果并不是我们想要的结果,因为引号的问题。所以我们会想到另外的办法:

>>> 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'"

同样会有引号的问题,这个时候我们可以通过这个字符串去掉前后的双引号来达到目的。

但是,其实我们还有一种更安全更方便的方式,如下:

>>> a = ['1.1.1.1','2.2.2.2','3.3.3.3']                                                  
>>> select_str = 'select * from server where ip in (%s)' % ','.join(['%s'] * len(a))     
>>> select_str
'select * from server where ip in (%s,%s,%s)'

这里我们先根据Ip列表的长度来生成对应的参数位置,然后通过MySQLdb模块中的execute函数来执行:

cursor.execute(select_str,a)

这样子就可以了

  • 作者:云中不知人
  • 原文链接:https://blog.csdn.net/u011085172/article/details/79044490
    更新时间:2023年1月21日11:57:22 ,共 674 字。