现在的位置: 首页 > 综合 > 正文

MySQL导入导出CSV文件

2013年10月31日 ⁄ 综合 ⁄ 共 2409字 ⁄ 字号 评论关闭

MySQL中导出CSV格式数据的SQL语句样本如下:

FIELDS TERMINATED BY ---- 字段终止字符
FIELDS OPTIONALLY ENCLOSED BY ---- 封套符
LINES TERMINATED BY ---- 行终止符


MYSQL   LOAD DATA INFILE命令可以把csv平面文件中的数据导入到数据库中。

linux下:

  1. LOAD DATA INFILE '/home/test/dump/ip_location.csv'
  2.  INTO TABLE ip_location
  3.  CHARACTER SET utf8
  4.  FIELDS TERMINATED BY ',' ENCLOSED BY '"';

--CHARACTER SET :mysql字符集,一定要加上,免去乱码麻烦
--INTO TABLE :导入到哪个表
--FIELDS TERMINATED BY :以什么作为分割符
-- ENCLOSED BY :被什么包围



windows:

  1. LOAD DATA INFILE "d:/insert_data.csv"
  2.  REPLACE INTO TABLE DEMO
  3.  CHARACTER SET gb2312
  4.  FIELDS TERMINATED BY "," ENCLOSED BY ""
  5.  LINES TERMINATED BY "\r\n";

--LINES TERMINATED BY:这个与linux不同,以什么作为一行的结尾。

Sql代码  收藏代码
  1. select * from test_info   
  2. into outfile '/tmp/test.csv'   
  3. fields terminated by ',' optionally enclosed by '"' escaped by '"'   
  4. lines terminated by '\r\n';   
  1. select * from test_info   
  2. into outfile '/tmp/test.csv'   
  3. fields terminated by ',' optionally enclosed by '"' escaped by '"'   
  4. lines terminated by '\r\n';   

MySQL中导入CSV格式数据的SQL语句样本如下:

Sql代码  收藏代码
  1. load data infile '/tmp/test.csv'   
  2. into table test_info    
  3. fields terminated by ','  optionally enclosed by '"' escaped by '"'   
  4. lines terminated by '\r\n';   
  1. load data infile '/tmp/test.csv'   
  2. into table test_info    
  3. fields terminated by ','  optionally enclosed by '"' escaped by '"'   
  4. lines terminated by '\r\n';   

里面最关键的部分就是格式参数

Sql代码  收藏代码
  1. fields terminated by ',' optionally enclosed by '"' escaped by '"'   
  2. lines terminated by '\r\n'   
  1. fields terminated by ',' optionally enclosed by '"' escaped by '"'   
  2. lines terminated by '\r\n'   

这个参数是根据RFC4180文档设置的,该文档全称Common Format and MIME Type for Comma-Separated Values (CSV) Files,其中详细描述了CSV格式,其要点包括:

(1)字段之间以逗号分隔,数据行之间以\r\n分隔;

(2)字符串以半角双引号包围,字符串本身的双引号用两个双引号表示。

 

文件:test_csv.sql

Sql代码  收藏代码
  1. use test;  
  2.   
  3. create table test_info (  
  4.     id  integer not null,  
  5.     content varchar(64) not null,  
  6.     primary key (id)  
  7. );  
  8.   
  9. delete from test_info;  
  10.   
  11. insert into test_info values (2010, 'hello, line  
  12. suped  
  13. seped  
  14. "  
  15. end'  
  16. );  
  17.   
  18. select * from test_info;  
  19.   
  20. select * from test_info into outfile '/tmp/test.csv' fields terminated by ',' optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';  
  21.   
  22. delete from test_info;  
  23.   
  24. load data infile '/tmp/test.csv' into table test_info  fields terminated by ','  optionally enclosed by '"' escaped by '"' lines terminated by '\r\n';  
  25.   
  26. select * from test_info;  
  27.   
  28.    
  1. use test;  
  2.   
  3. create table test_info (  
  4.     id  integer

抱歉!评论已关闭.