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

2023年1月19日08:59:24

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

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

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)

这样子就可以了

补充知识:python中pymysql使用in时候的传参方式

# 注意这里使用in时候传参的方式 {topic_list}这不用加引号,是因为里面需要的值 topic_id是int

sql = "select f_topic_id, f_topic_name, f_partition_num, f_replicas_factor, f_cluster_id, f_topic_token, f_log_retention_time, f_created_at, f_created_by, f_modified_at, f_modified_by from tkafka_topic where f_topic_id in ({topic_list});".format(topic_list=topic_list)

总结:

以前一开始以为传参是看传过来的参数是什么类型来加引号的,int不加引号,str加引号

但是今天才知道,看的是里面接收参数的变量需要什么类型来加引号的。

以上这篇python 解决mysql where in 对列表(list,,array)问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持云海天教程。

原文链接:https://blog.csdn.net/u011085172/article/details/79044490

  • 作者:第一航
  • 原文链接:https://blog.csdn.net/weixin_30215717/article/details/113334108
    更新时间:2023年1月19日08:59:24 ,共 1232 字。