例如有這麼一個查詢語句:
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加引號
但是今天才知道,看的是裡面接收參數的變量需要什麼類型來加引號的。
[e36605 ] python 解決mysql where in 對列表(list,,array)問題已經有244次圍觀