下面来看两个mysql 导入导出CSV数据的例子,这此都用到了mysql自带的命令了,如 LOAD DATA LOCAL INFILE 或select * INTO OUTFILE命令了.
cvs文件导入MySql数据库命令,代码如下:
- setnamesutf8;
- LOADDATALOCALINFILE'C:\\resource.csv'
- INTOTABLEresource
- FIELDSTERMINATEDBY''
- LINESTERMINATEDBY'\r\n'
- (title,singer);
- --phpfensi.com
- FIELDSTERMINATEDBY----字段终止字符
- OPTIONALLYENCLOSEDBY----封套符
- LINESTERMINATEDBY----行终止符
导出一段时间的数据到 cvs,代码如下:
fileName="data"`date --date=$date "+%Y%m%d"`".csv";
#mysql里先导出数据到 xml, 用 select into outfile 导出,设定字段分隔符和记录分隔符.
/usr/local/webserver/mysql/bin/mysql -h "$mysql_host" -u "$mysql_username" --password="$mysql_password" -e "select * INTO OUTFILE '$data_dir$fileName' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n' from $table where InTime>=$minTime && InTime<$maxTime;"
#这一步也很重要, 需要将编码转换为GBK
rm -rf $final_dir$fileName && touch $final_dir$fileName
iconv -c -f UTF-8 -t GBK $data_dir$fileName > $final_dir$fileName
先用select into outfile 把数据从mysql 里边倒出来,其中字段分隔符 \t,记录分隔符为 \n,然后转一下字符的编码就OK了.