如何使用perl脚本将mysql结果导出到csv文件中

时间:2015-05-16 09:07:49

标签: mysql perl csv

我心爱的perl脚本代码,

#!/usr/bin/perl -w
..
.// db connection
..
$sth=$dbh->prepare(" SELECT * FROM Table_nm ") or warn $dbh->errstr;
$sth->execute or die "can't execute the query: $sth1->errstr";

// I want to export the result of mysql query into csv file.

请帮忙。感谢名单!

1 个答案:

答案 0 :(得分:0)

除非您需要在将结果集输出到csv文件之前对其进行处理,否则通过调整sql语句直接导出它会更有效。

find . -type f -exec awk ... {} ;

13.2.9.1 SELECT ... INTO Syntax

修改 为了能够获得标题行,您需要添加第二个select语句,该语句指定与其他select语句的字段和union。

示例:

SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM test_table;
mysql> select 'OTOBJID','OTTRANSID'
union
select * into outfile 'd:/test.csv'
fields terminated by ','
optionally enclosed by '"'
from objecttransports;