225025 发表于 2017-12-13 06:13:08

在MySQL中快速的插入大量测试数据

  很多时候为了测试数据库设计是否恰当,优化SQL语句,需要在表中插入大量的数据,怎么插入大量的数据就是个问题了。
  最开始想到的办法就是写一个程序通过一个很大的循环来不停的插入,比如这样:
  

int i = LOOP_COUNT;  
while(i-->=0){
  
//insert data here.
  
}
  

  

  不过我在这么做的时候发现这样插入数据非常的慢,一秒钟插入的数据量还不到100条,于是想到不要一条一条的插入,而是通过
  

INSERT INTO TABLE VALUES (),(),(),()...  

  

  这样的方式来插入。于是修改程序为:
  

int i = LOOP_COUNT;  
StringBuilder stringBuilder;
  
while(i-->=0){
  
if(LOOP_COUNT!=i && i%5000==0){
  
//通过insert values的方式插入这5000条数据并清空stringBuilder
  
}
  
stringBuilder.append("(数据)");
  
}
  
//插入剩余的数据
  

  

  这样做的插入速度是上升了很多,不过如果想要插入大量的输入,比如上亿条,那么花费的时间还是非常长的。
  查询MySQL的文档,发现了一个页面:LOAD DATA INFILE 光看这个名字,觉得有戏,于是仔细看了下。
  官方对于这个命令的描述是:
  

LOAD DATA INFILE 'file_name'  

  
INTO TABLE tbl_name
  

  
[{FIELDS | COLUMNS}
  

  
[ ENCLOSED BY 'char']
  

  
]
  
[LINES
  

  

  
]
  

  
[(col_name_or_user_var,...)]
  

  

  

  命令不复杂,具体的每个参数的意义和用法请看官方的解释 http://dev.mysql.com/doc/refman/5.5/en/load-data.html
  那么现在做的就是生成数据了,我习惯用\t作为数据的分隔符、用\n作为一行的分隔符,所以生成数据的代码如下:
  

long start = System.currentTimeMillis() / 1000;  
try {
  
File file = new File(FILE);
  

  
if (file.exists()) {
  
file.delete();
  
}
  
file.createNewFile();
  

  
FileOutputStream outStream = new FileOutputStream(file, true);
  

  
StringBuilder builder = new StringBuilder(10240);
  
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
  
Random rand = new Random();
  

  
String tmpDate = dateFormat.format(new Date());
  
Long tmpTimestamp = System.currentTimeMillis() / 1000;
  

  
int i = 0;
  
while (i++ < LOOP) {
  
if (i > 0 && i % 30000 == 0) {
  
System.out.println("write offset:" + i);
  
outStream.write(builder.toString().getBytes(CHARCODE));
  
builder = new StringBuilder(10240);
  
}
  

  
if (tmpTimestamp.compareTo(System.currentTimeMillis() / 1000) != 0) {
  
tmpDate = dateFormat.format(new Date());
  
tmpTimestamp = System.currentTimeMillis() / 1000;
  
}
  

  
builder.append(tmpDate);
  
builder.append("\t");
  
builder.append(rand.nextInt(999));
  
builder.append("\t");
  
builder.append(Encrypt.md5(System.currentTimeMillis() + "" + rand.nextInt(99999999)));
  
builder.append("\t");
  
builder.append(rand.nextInt(999) % 2 == 0 ? "AA." : "BB");
  
builder.append("\t");
  
builder.append(rand.nextFloat() * 2000);
  
builder.append("\t");
  
builder.append(rand.nextInt(9));
  
builder.append("\n");
  
}
  

  
System.out.println("write data:" + i);
  
outStream.write(builder.toString().getBytes(CHARCODE));
  

  
outStream.close();
  
} catch (Exception e) {
  
e.printStackTrace();
  
}
  

  
System.out.println(System.currentTimeMillis() / 1000 - start);
  

  

  这段代码会生成一个数据文件,每一行为一条记录,然后再使用上面提到的 LOAD DATA 来导入数据就可以了,我在公司的电脑下(2G内存+垃圾双核CPU,MySQL直接装在windows下,没任何优化,developer模式)每秒能达到近万条的插入速度,比其他方式都快很多。
  另外如果想直接用GUI工具操作也可以,比如SQLYog中,右键要导入的表,选择Import – Import CSV Data Using Load Local.. 然后设置好编码、分隔符后就可以直接导入了。
页: [1]
查看完整版本: 在MySQL中快速的插入大量测试数据