1. create_sql.pl will read csv file and it will create an out put file 2. the filename.sql will contain following sql statement syntax: create table ( , .....); 3. is also table name. 4. the second column of csv file is column name, third column is data type as description of heading. 将csv文件转换成创建sql数据表的语句:
#/usr/bin/perl
#use warnings;
$file=$ARGV[0]; #打开CSV文件将“去掉并存放到csv.txt文件中
open(CSV,"$file")ordie"can't open $file.csv :$!\n"; foreach$_(<CSV>) { chomp; s/\"//gim;
`echo $_>>'csv.txt'`; } close CSV; #子例程,获取每行的每个元素存放到数组@tmp中; sub line{ for(my $i=0;$i<@arr;$i++){ $tmp[$i]=$arr[$i]; if ($tmp[5]=""){ $tmp[5]="NOT NULL"; } else {$tmp[5]="NULL";}
} } $txt='csv.txt'; open (SQL,"$txt") or die "can't open csv.txt\n"; #$table用来存放sql公共部分 $tablename=$file; $tablename=~s/csv/sql/i; $table1="create table ".$tablename ." (\n"; $table3=")\n"; $table4="alter table ".$tablename."\n"; #读取csv.txt文件,并以,为分隔符分开存放数组@arr; while($sql=) { chomp($sql); @arr=split /,/,$sql; #调用子例程 $n=&line; #创建sql语句的每个字段; $table2=$tmp[1]." ". $tmp[2]." (".$tmp[3]." )"." ". $tmp[5].","." as " .$tmp[6]."\n";
$table6.=$table2; $table7.=$table5; } $table=$table1.$table6.$table3.$table4.$table7; #将命令写入sql文件中; open TABLE ,">> $tablename" or die "can't open$tablename$!\n"; print TABLE $table; close TABLE;