csv数据导入mysql方法

mysql自己有个csv引擎,可以通过这个引擎来实现将csv中的数据导入到mysql数据库中,并且速度比通过php或是python写的批处理程序快的多。

具体的实现代码示例:

load data infile '/tmp/file.csv' into table _tablename (set character utf8)
fields terminated by ','
enclosed by '"'
lines terminated by '\r\n';

 这段代码中涉及的一些关键字的解释如下:

fields terminated by '':这是指出csv文件中字段终止符,也就是数据之间的分隔符;

enclosed by '':指出封套符;

lines terminated by '':指行终止符

在csv文档(RFC4180)中详细介绍了csv的格式,其中的要点有:

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

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

通过以上的解释,详细对于数据导入代码应该有更好的理解了。

 

同样的,csv数据能够导入mysql数据库中,mysql中的数据表也能导出csv文件,导出的代码示例:

select * from tablename into outfile '/tmp/data.txt' 
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n';

 当将数据库中的数据导出到文件后,要再将数据导入到数据库中,必须遵守导出时的文件中定义的格式。

 

参考:

http://www.cnblogs.com/zeroone/archive/2013/01/12/2857388.html

http://dev.mysql.com/doc/refman/5.1/zh/sql-syntax.html#load-data

 

posted @ 2013-02-04 19:49  新的凯斯  阅读(683)  评论(0编辑  收藏  举报