快速为MySQL创建大量测试数据

快速为MySQL创建大量测试数据 :

  1. 引言
    在PostgreSQL中可以用generate_series()函数来快速生成大量测试数据,在MySQL中没有提供类似的东西。那么在做测试的时候,要往表中插入大量数据库该怎么办?可以写一个循环执行INSERT语句的存储过程,但这种方式还是太慢,我试了下,1秒钟居然只能插500条记录。比较快的方式是用程序生成一个数据文件,再用load data加载。但是直接用程序生成最终的测试数据的方式又不够灵活,因此我们可以借鉴generate_series()先做一个功能与之类似的临时数据表,再通过这个临时数据表生成大量测试数据。下面演示一下过程。

  2. 生成类似于generate_series()的临时数据表
    创建临时数据表tmp_series

create table tmp_series(id int,primary key(id));
用python生成100w记录的数据文件
python -c "for i in range(1,1+1000000): print(i)">100w.txt
也可以直接用bash做,但bash的方式要比python慢得多
[chenhj@localhost ~]$ i=1;while [ $i -le 1000000 ];do echo $i ;let i+=1; done >100w.txt
导入数据到tmp_series表
mysql> load data infile '/home/chenhj/100w.txt' replace into table tmp_series;
Query OK, 1000000 rows affected (9.66 sec)
Records: 1000000 Deleted: 0 Skipped: 0 Warnings: 0
生成100w记录花了9秒多。

  1. 生成测试数据
    创建测试数据表

create table tb1(id int,c1 int,c2 varchar(100),primary key(id))

通过tmp_series表生成并插入测试数据,测试数据的计算方法可以自由发挥。
mysql> insert into tb1 select id,round(rand()*100000),concat('testdatatestdatatestdata',id) from tmp_series;
Query OK, 1000000 rows affected (11.03 sec)
Records: 1000000 Duplicates: 0 Warnings: 0
生成100w记录花了11秒,是不是挺快的!
最后生成的测试数据是长这样的。

mysql> select * from tb1 order by id limit 2;
id c1 c2
1 648 testdatatestdatatestdata1
2 111 testdatatestdatatestdata2

2 rows in set (0.00 sec)

如果只想生成小的数据集,比如1000条记录,可以使用limit。
insert into tb1 select id,round(rand()*1000),concat('testdatatestdatatestdata',id) from tmp_series order by id limit 1000;

你可能感兴趣的:(mysql)