使用DBI模块来批量插入数据库

这个是去年管理测试环境的时候,直接用脚本批量操作数据库
[pl]
#!/usr/bin/perl -w
use DBI;
use strict;
my $dbh;
my $INFILE=$ARGV[0];
open LIST ,"<$INFILE" or die "can’t open $INFILE\n";
my $table="table_appinfo";
$dbh=&connect();
my $qurey=qq{insert into $table (ip,name,manage,dev,location) values(?,?,?,?,?) };
my $sth=$dbh->prepare($qurey) || die $dbh->errstr;
my $dev="lab";
my $manage="namexxx";
my $location=’location’;
while(my $line=<LIST>){
my ($ip,$name)=split /\s+/,$line;
$sth->execute($ip,$name,$manage,$dev,$location);
print "insert $ip $name\n";
}
$dbh->disconnect();

exit(0);
##############################
sub connect() {
my $source=q{DBI:mysql:database=xxx;host=xx.xx.xx};
my $user="xxx";
my $passwd="xxxx";
my $dbh0=DBI->connect($source,$user,$passwd,{RaiseError=>1}) or die "connect mysql failed.";
$dbh0->do("SET character_set_client = ‘gb2312’");
$dbh0->do("SET character_set_connection = ‘gb2312’");
$dbh0->do("SET character_set_results= ‘gb2312’"); #解决GBK编码问题
return $dbh0;
}
[/pl]

此条目发表在Perl Script分类目录。将固定链接加入收藏夹。

发表评论