Chinaunix首页 | 论坛 | 博客
  • 博客访问: 467919
  • 博文数量: 279
  • 博客积分: 4467
  • 博客等级: 上校
  • 技术积分: 2830
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-03 14:43
文章分类

全部博文(279)

文章存档

2013年(1)

2012年(39)

2011年(35)

2009年(29)

2008年(131)

2007年(44)

分类:

2007-11-30 15:26:32

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") or die "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";

$table5="add constraint default unique"." (".$tmp[4].")\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;

close SQL;
unlink "
csv.txt

阅读(296) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~