之前都是在mysql的存储过程中插入数据,毕竟mysql语法函数有限,很多都有限制。突然想到学了python正好可以练练手。
首先需要安装pymysql模块包(模块包安装请自行百度)
 1 #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

  

12-20 16:36