python连接mysql循环插入千万条数据脚本
时间:2021-07-01 10:21:17
帮助过:16人阅读
#encoding:utf-8
2 import pymysql
3 import time
4 import random
5 #连接mysql
6 db = pymysql.connect(
‘14.29.249.74‘,
‘kx_admin‘,
‘Yjh7yC0L7L1G1k6qXKwb‘,
‘ilock‘)
7 #获取mysql操作光标
8 cursor =
db.cursor()
9 #初始化变量
10 count =
0
11 #设置sql语句循环次数
12 while count <= 100
:
13 count += 1
14 #定义mysql字段的范围随机数变量
15 num = random.randint(0,2
)
16 memo_num = random.randint(100,111
)
17 city_list = [
‘长沙‘,
‘湘潭‘,
‘株洲‘,
‘衡阳‘]
18 a =
random.choice(city_list)
19 #生成mysql语句插入语句
20 sql =
"insert into iodn_city(city_code,city_name,memo)values(%s,‘%s‘,%s)" %
(num,a,memo_num)
21 #执行sql语句
22 try:
23 cursor.execute(sql)
24 db.commit()
25 #错误回滚
26 except:
27 db.rollback()
28 #关闭mysql
29 db.close()
View Code
python连接mysql循环插入千万条数据脚本
标签:回滚 初始 close values lis display lap commit lock