[MySql]使用LOAD DATA导入数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[MySql]使用LOAD DATA导入数据相关的知识,希望对你有一定的参考价值。

LOAD DATA导入数据语法:

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE ‘file_name‘
    [REPLACE | IGNORE]
    INTO TABLE tbl_name
    [PARTITION (partition_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 | ROWS}]
    [(col_name_or_user_var,...)]
    [SET col_name = expr,...]

  

FIELDS和LINES都是可选的,但是如果都指定了,FIELDS必须在LINES之前。

本地用一个pet表,结构如下:

+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| name    | varchar(20) | YES  |     | NULL    |       |
| owner   | varchar(20) | YES  |     | NULL    |       |
| species | varchar(20) | YES  |     | NULL    |       |
| sex     | char(1)     | YES  |     | NULL    |       |
| birth   | date        | YES  |     | NULL    |       |
| death   | date        | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+

  

要导入的数据:pet.txt

Fluffy,Harold,cat,f,1993-02-04
Claws,Gwen,cat,m,1994-03-17
Buffy,Harold,dog,f,1989-05-13
Fang,Benny,dog,m,1990-08-27
Bowser,Diane,dog,m,1979-08-31,1995-07-29
Chirpy,Gwen,bird,f,1998-09-11
Whistler,Gwen,bird, ,1997-12-09
Slim,Benny,snake,m,1996-04-29

  

导入命令:

LOAD DATA LOCAL INFILE ‘/home/scott/mysql/pet.txt‘ IGNORE INTO TABLE pet fields TERMINATED BY ‘,‘ lines TERMINATED BY ‘\n‘;

  

导入结果:

mysql> select * from pet;
+----------+--------+---------+------+------------+------------+
| name     | owner  | species | sex  | birth      | death      |
+----------+--------+---------+------+------------+------------+
| Fluffy   | Harold | cat     | f    | 1993-02-04 | NULL       |
| Claws    | Gwen   | cat     | m    | 1994-03-17 | NULL       |
| Buffy    | Harold | dog     | f    | 1989-05-13 | NULL       |
| Fang     | Benny  | dog     | m    | 1990-08-27 | NULL       |
| Bowser   | Diane  | dog     | m    | 1979-08-31 | 1995-07-29 |
| Chirpy   | Gwen   | bird    | f    | 1998-09-11 | NULL       |
| Whistler | Gwen   | bird    |      | 1997-12-09 | NULL       |
| Slim     | Benny  | snake   | m    | 1996-04-29 | NULL       |
+----------+--------+---------+------+------------+------------+

  

 

以上是关于[MySql]使用LOAD DATA导入数据的主要内容,如果未能解决你的问题,请参考以下文章

MYSQL 使用 LOAD DATA INFILE 从 csv 导入数据

mysql导入数据load data infile用法整理

MySQL LOAD DATA INFILE—批量从文件(csvtxt)导入数据

MySQL使用load data导入数据错误的一个场景

MySQL使用load data导入数据错误的一个场景

mysql 语句LOAD DATA INFILE高效导入数据