mysql導(dǎo)入數(shù)據(jù)
瀏覽量:2498
mysqlimport
示例
mysqlimport -uroot -p123456 test /tmp/mytbl.txt;
約定:文件名的最后一部分為表名,以上語(yǔ)句導(dǎo)入到表mytbl
mysqlimport必須指定數(shù)據(jù)庫(kù),以上語(yǔ)句數(shù)據(jù)庫(kù)為test
導(dǎo)入csv
mysqlimport -uroot -p --local --lines-terminated-by="\r\n" --fields-terminated-by="," --fields-enclosed-by="\"" test /tmp/mytbl.csv
load data
示例
mysql> load data infile '/tmp/mytbl.txt' into table mytbl
load data可以不指定數(shù)據(jù)庫(kù)
以上語(yǔ)句中,mysql必須有/tmp/的讀權(quán)限
導(dǎo)入csv
mysql> load data infile '/tmp/mytbl.csv' into table mytbl fields terminated by ',' enclosed by '"' lines terminated by '\r\n'
處理重復(fù)主鍵
替換已有值
mysql> load data infile '/tmp/mytbl.txt' replace into table mytbl fields terminated by '\t' lines terminated by '\n'
表中已有則不導(dǎo)入
mysql> load data infile '/tmp/mytbl.csv' ignore into table mytbl fields terminated by ',' enclosed by '"' lines terminated by '\r\n'
跳過(guò)文件行
以下示例為跳過(guò)第一行
mysql> load data infile '/tmp/mytbl.txt' into table mytbl ignore 1 lines;
預(yù)處理
文件data.txt內(nèi)容:
Date Time Name
Weight State
2006-09-01 12:00:00 Bill Wills
200 Nevada
2006-09-02 09:00:00 Jeff Deft
150 Oklahoma
2006-09-04 03:00:00 Bob Hobbs
225 Utah
2006-09-07 08:00:00 Hank Banks
175 Texas
文件必須被加載入如下的表
create table tbl
(
dt datetime,
last_name char(10),
first_name char(10),
weight_kg float,
st_abbrev char(2)
)
create table states
(
name varchar(20),
shortname char(2)
)
states 表中內(nèi)容:
name shortname
Nevada NV
Oklahoma OK
Utah UT
Texas TX
insert into states
values('Nevada','NV')
,('Oklahoma','OK')
,('Utah', 'UT')
,('Texas', 'TX')
導(dǎo)入:
load data infile '/tmp/data.txt' into table tbl
ignore 1 lines
(@date,@time,@name,@weight_lb,@state)
set dt=concat(@date,' ',@time),
first_name=substring_index(@name,' ',1),
last_name=substring_index(@name,' ',-1),
weight_kg=@weight_lb * .454,
st_abbrev = (select shortname from states where name=@state);
結(jié)果:
mysql> select * from tbl; +---------------------+-----------+------------+-----------+-----------+
| dt | last_name | first_name | weight_kg | st_abbrev |
+---------------------+-----------+------------+-----------+-----------+
| 2006-09-01 12:00:00 | Wills | Bill | 90.8 | NV |
| 2006-09-02 09:00:00 | Deft | Jeff | 68.1 | OK |
| 2006-09-04 03:00:00 | Hobbs | Bob | 102.15 | UT |
| 2006-09-07 08:00:00 | Banks | Hank | 79.45 | TX |
+---------------------+-----------+------------+-----------+-----------+
將windows本地文件導(dǎo)入到linux下的mysql數(shù)據(jù)庫(kù),加local
load data local infile 'C:/mytbl.txt' into table mytbl fields terminated by '\t' lines terminated by '\r\n'