python实现:向数据库中插入100条测试数据
创建表:
create table studentInfo( ID int not null auto_increment comment "不为空的自增长的主键ID", student_id varchar(20) not null, name varchar(30) not null, sex char(4), tel varchar(13) unique not null, AdmissionDate datetime default '0000:00:00 00:00:00', primary key (ID), #每个表都要有主键,一般都在ID列 unique student_id(student_id) #索引。unique为索引时这一列数据不能都有重复。不能插入相同数据。想插入同数据,可以用 key、 index )engine=innodb character set utf8 comment "学生信息表";
create table grade( ID int auto_increment not null, stuID varchar(20), course varchar(20) not null, score tinyint(4) default 0, primary key (ID), key idx_stuid(stuID), #设置索引 CONSTRAINT FK_ID FOREIGN KEY(stuID) REFERENCES studentInfo(student_id) )engine=innodb character set utf8 comment "学生成绩表"; #外键,字段:stuID 关联上个表的student_id字段。在grade生成数据的话,在grade插入的数据的stuID 必须存在于studentInfo表。删的时候也不能单独删。
python脚本:
要先安装pymysql:
pip install pymysql==0.7.6
import pymysql import random def insertData(): conn = pymysql.connect( # pymysql.connect连接数据库 host = "127.0.0.1", port = 3306, user = "root", passwd = "gloryroad", db = "testnewman", charset = "utf8") cur = conn.cursor() #获取数据库的游标,指向要操作的哪个库、哪个表、哪行记录 conn.select_db('gloryroad') #选择要操作的库,可以不写,默认是连接的库db = "testnewman", courseList = ['python', 'java', 'mysql', 'linux', '接口测试', '性能测试', '自动化测试','数据结构与算法'] for i in range(1, 101): student_id = '201803' + '0' * (3 - len(str(i))) + str(i) #201803001(最少没有0,最多2个0) name = random.choice(['Lucy','Tom','Lily','Amy','Dave','Aaron','Baron']) + str(i) tel = '1' + str(random.choice([3, 5, 7, 8])) + str(random.random())[2:11] sex = random.choice(['女', '男']) stuinfo_sql = "insert into studentInfo(student_id, name, sex, tel, AdmissionDate) \ values('%s', '%s', '%s', '%s', date_sub(now(),interval %s day))" \ %(student_id, name, sex, tel, random.randint(90, 120)) cur.execute(stuinfo_sql) #sql语句存到变量中 conn.commit() #插入数据完后提交数据 for j in courseList: grade_sql = "insert into grade(stuID,course,score) values('%s','%s',%s)" %(student_id,j,random.randint(80, 100)) cur.execute(grade_sql) cur.close() #游标关闭 conn.commit() conn.close() #连接关闭 insertData() print("数据插入结束!")
代码思路:连接数据库-获取游标-拼好sql-执行sql-提交数据-关闭游标-关闭链接