一,准备数据库,创建表,导入ip,事先国家省城市都是空的,后面查询写入
CREATE TABLE `comsumer10` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `c0` int(11) NOT NULL, `c1` int(11) DEFAULT NULL, `c2` double(64,2) NOT NULL, `ip` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `country` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `region` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `city` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2612 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
二,python安装 ipip-datx,pymysql模块,https://github.com/hrghrghg/datx-python
#!_*_coding:utf-8_*_ #__author__:"Alex huang" import datx,pymysql def check_ip(ip): c = datx.City("17monipdb.datx") return c.find(ip) def get_conn(): conn = pymysql.connect(host='192.168.80.200', port=3306, user='root', passwd='123', db='django', charset='utf8') return conn def query_all(cur, sql, args): cur.execute(sql, args) return cur.fetchall() def ip_region(): conn = get_conn() cur = conn.cursor() k=0 sql_ip = 'select ip from comsumer10 where country is NULL limit 10;' results=query_all(cur=cur,sql=sql_ip,args=None) for i in results: res = check_ip(i[0]) #获取指定ip的归属地函数 if res: sql_add = "update comsumer10 set country='"+res[0]+"',region='"+res[1]+"',city='"+res[2]+"' where ip='"+i[0]+"';" print(sql_add) cur.execute(sql_add) conn.commit() k = k+1 print("===>:",k,"(",len(results),")") cur.close() conn.close() if __name__ == '__main__': ip_region()