您的位置:首页 > 编程语言 > PHP开发

MySQL大批量数据插入,PHP之for不断插入时出现缓慢的解决方案及优化。

2014-03-13 15:25 627 查看
很多时候为了测试数据库设计是否恰当,优化SQL语句,需要在表中插入大量的数据,怎么插入大量的数据就是个问题了。

最开始想到的办法就是写一个程序通过一个很大的循环来不停的插入,比如这样:

1
2
3
4

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

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

1

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

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

1
2
3
45
6
7
8
9

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 光看这个名字,觉得有戏,于是仔细看了下。

官方对于这个命令的描述是:

1
2
3
45
6
7
8
9
10
1112
13
14
15
16

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name'
    [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [CHARACTER SET charset_name]
    [{FIELDS | COLUMNS}
        [TERMINATED BY 'string']
        [[OPTIONALLY] ENCLOSED BY 'char']
        [ESCAPED BY 'char']
    ]
    [LINES
        [STARTING BY 'string']
        [TERMINATED BY 'string']
    ]
    [IGNORE number LINES]
    [(col_name_or_user_var,...)]
    [SET col_name = expr,...]

命令不复杂,具体的每个参数的意义和用法请看官方的解释 http://dev.mysql.com/doc/refman/5.5/en/load-data.html

那么现在做的就是生成数据了,我习惯用\t作为数据的分隔符、用\n作为一行的分隔符,所以生成数据的代码如下:

1
2
3
45
6
7
8
9
10
1112
13
14
15
16
17
18
19
20
2122
23
24
25
26
27
28
29
30
3132
33
34
35
36
37
38
39
40
4142
43
44
45
46
47
48
49
50
5152
53
54

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.. 然后设置好编码、分隔符后就可以直接导入了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐