共計 2460 個字符,預計需要花費 7 分鐘才能閱讀完成。
這篇文章主要介紹“mysql 怎么導入數據”,在日常操作中,相信很多人在 mysql 怎么導入數據問題上存在疑惑,丸趣 TV 小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”mysql 怎么導入數據”的疑惑有所幫助!接下來,請跟著丸趣 TV 小編一起來學習吧!
mysqlimport
示例
mysqlimport -uroot -p123456 test /tmp/mytbl.txt;
約定:文件名的最后一部分為表名,以上語句導入到表 mytbl
mysqlimport 必須指定數據庫,以上語句數據庫為 test
www.2cto.com
導入 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 可以不指定數據庫
以上語句中,mysql 必須有 /tmp/ 的讀權限
導入 csv
mysql load data infile /tmp/mytbl.csv into table mytbl fields terminated by , enclosed by lines terminated by \r\n
www.2cto.com
處理重復主鍵
替換已有值
mysql load data infile /tmp/mytbl.txt replace into table mytbl fields terminated by \t lines terminated by \n
表中已有則不導入
mysql load data infile /tmp/mytbl.csv ignore into table mytbl fields terminated by , enclosed by lines terminated by \r\n
跳過文件行
以下示例為跳過第一行
mysql load data infile /tmp/mytbl.txt into table mytbl ignore 1 lines;
預處理
文件 data.txt 內容:
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)
) www.2cto.com
states 表中內容:
name shortname
Nevada NV
Oklahoma OK
Utah UT
Texas TX
insert into states
values(Nevada , NV)
,(Oklahoma , OK)
,(Utah , UT)
,(Texas , TX)
導入:
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);
結果:
mysql select * from tbl; www.2cto.com +———————+———–+————+———–+———–+
| 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 |
+———————+———–+————+———–+———–+
將本地文件導入到 linux 下的 mysql,加 local
load data local infile C:/mytbl.txt into table mytbl fields terminated by \t lines terminated by \r\n
到此,關于“mysql 怎么導入數據”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注丸趣 TV 網站,丸趣 TV 小編會繼續努力為大家帶來更多實用的文章!