1.導入
基本語法: load data [low_priority] [local] infile 'file_name txt' [replace | ignore] into table tbl_name [character set gbk] [fields [terminated by't'] [OPTIONALLY] enclosed by ''] [escaped by'\' ]]
[lines terminated by'n'] [ignore number lines] [(col_name, )]
導入實例
1 load data infile 'csv文件路徑\\test.csv'
2 replace into table 表名 3 fields terminated by ','
4 optionally enclosed by '"'
5 lines terminated by '\r\n'
6 ignore 1 lines(Id,@name,password);
說明:
第一行就是導入文件;
第二行參看語法就會發現有兩個詞:replace 和 ignore 。replace和ignore關鍵詞控制對現有的唯一鍵記錄的重復的處理。如果你指定replace,新行將代替有相同的唯一鍵值的現有行。如果你指定ignore,跳過有唯一鍵的現有行的重復行的輸入。如果你不指定任何一個選項,當找到重復鍵時,出現一個錯誤,並且文本文件的余下部分被忽略。
第三~四行很簡單就是每個具體字段內容之間是以逗號隔開的,那就以逗號分開。 erminated by描述字段的分隔符,默認情況下是tab字符(\t) 。enclosed by描述的是字段的括起字符,就是說字段中如果有引號,就當做是字段的一部分。 語法中還有一個是 escaped by, 它描述的是轉義字符。默認的是反斜杠(backslash:\ )
第五行 lines terminated by是對每行進行分割,這里要注意一個問題,如果csv文件是在windows下生成,那分割用 ‘\r\n’,linux下用 ‘\n’。
第六行中 ignore 1 lines 是忽略第一行,因為第一行往往是字段名,后邊括號中有個字段很特別 @name,它是說如果csv文件中有個字段我不想插進去,那就把對應字段名變成@name.
具體操作:
step1.准備CSV文件
1.在數據庫中建test數據表,表屬性如下:
2.csv文件的存儲內容如下,命名為test1.csv,存儲位置:“C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv”:

驗證.csv編碼格式是否正確,務必保證導入數據的編碼格式是ANSI編碼格式
step2.數據導入:
1.查詢已有數據庫:show databases;
2.使用這個數據庫,使用命令:use flight_analysis;
3.查詢我們之前建立的表格test是否在test數據庫中,使用命令:show tables;
4.導入數據庫:
#導入數據中不包含中文
1 load data infile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv' --CSV文件存放路徑 2 3 into test student--要將數據導入的表名 4 5 fields terminated by ',' optionally enclosed by '"' escaped by '"' 6 7 lines terminated by '\r\n';
#導入數據中包含中文
load data infile 'C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/test1.csv' --CSV文件存放路徑 into table test character set gb2312 --要將數據導入的表名 fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';
1 #忽略第一行 2 load data infile "C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/datatest1.csv" 3 into table data_test 4 fields terminated by ',' optionally enclosed by '"' escaped by '"' 5 lines terminated by '\r\n' 6 ignore 1 lines;
導出
1 select * from 表名 2 into outfile '導出路徑\\test.csv' 3 fields terminated by ',' 4 optionally enclosed by '"' 5 escaped by '"' 6 lines terminated by '\n';
