• 合理使用mysql中的load data infile导入数据


    基本语法:

    load data  [low_priority] [local] infile 'file_name txt' [replace | ignore]
    into table tbl_name
    [fields
    [terminated by't']
    [OPTIONALLY] enclosed by '']
    [escaped by'' ]]
    [lines terminated by'n']
    [ignore number lines]
    [(col_name,   )]
     
    load data infile语句从一个文本文件中以很高的速度读入一个表中。使用这个命令之前,mysqld进程(服务)必须已经在运行。为了安全原因,当读取位于服务器上的文本文件时,文件必须处于数据库目录或可被所有人读取。另外,为了对服务器上文件使用load data infile,在服务器主机上你必须有file的权限。


    把千万级甚至亿级的数据写入mysql,实在是一件很让人头痛的事情。
    load data local infile貌似是最快的方法了, 可是load一个亿级的文件,仍然需要数十分钟。

    如果有主从结构的话,在主服务器上面load数十分钟,文件数据会写入binary log,再传输到从服务器,
    然后从服务器也需要数十分钟来做load操作,如果从服务器只有一个sql_thread来执行binary log,那么在这数十分钟内,
    从服务器就只能做这一个load操作,无法对后续的sql语句做出响应,导致主从之间的延迟有数十分钟。

    而且,如果load了20分钟,www.111cn.net然后发现数据源有问题,需要取消load,那么mysql至少还要20分钟才能回滚成功…
    这个时候非常无奈。

    所以有必要把这种大文件拆分成若干个小文件,然后分别load.

    下面给出一些测试数据:

    [root@yw-0-0 huarong]# wc -l cfi.txt
    20894227 cfi.txt, 行数20M
    有九个字段,varchar(255),没有key。
    文件大小  4,078,099,848 (3.8G),每行平均195字节。
     
    t1.sh 直接load,作用是预热。
    这个时间数据竟然丢失了...
     
    innodb t1.sh 再次直接load
    time mysql   test -e "load data local infile '/d01/huarong/cfi.txt' into table cfi"
    [root@yw-0-0 huarong]# ./t1.sh
    real    6m4.720s
    user    0m0.492s
    sys     0m2.213s
     
    innodb t2.sh不写binlog.
    time mysql   test -e "set foreign_key_checks=0; set sql_log_bin=0; set unique_checks=0; load data local infile '/d01/huarong/cfi.txt' into table cfi" www.111cn.net
    [root@yw-0-0 huarong]# ./t2.sh
    real    5m3.964s
    user    0m0.586s
    sys     0m2.788s
     
    innodb t3.sh fifo,每次load 1M行数据。
    wget http://www.maatkit.org/get/mk-fifo-split
    perl ./mk-fifo-split ./cfi.txt --fifo /tmp/cfi.fifo --lines 1000000
    while [ -e /tmp/cfi.fifo ]; do
            time mysql   test -e "set foreign_key_checks=0; set sql_log_bin=0; set unique_checks=0; load data local infile '/tmp/cfi.fifo' into table cfi"
       sleep 1;
    done
     
    real: 5m25.84s
    user: 0m2.197s
    sys: 0m11.244s
     
     
    myisam: t2.sh不写binlog
    real    3m24.838s
    user    0m0.626s
    sys     0m2.939s

    更多详细内容请查看:http://www.111cn.net/database/mysql/56628.htm

  • 相关阅读:
    bzoj2049 [Sdoi2008]Cave 洞穴勘测——LCT
    洛谷P2679 子串——DP
    bzoj3669 [Noi2014]魔法森林——LCT
    洛谷P3778 [APIO2017]商旅——01分数规划
    bzoj4196 [Noi2015]软件包管理器——树链剖分
    bzoj4881 线段游戏——上升序列方案数
    bzoj1426 (洛谷P4550) 收集邮票——期望
    bzoj1858 [Scoi2010]序列操作——线段树
    bzoj3626 [LNOI2014]LCA——树链剖分
    L The Digits String(没有写完,有空补)
  • 原文地址:https://www.cnblogs.com/alibai/p/3585745.html
Copyright © 2020-2023  润新知