- 论坛徽章:
- 3
|
运行代码需要模块,具体如下:- package TDmodule;
- use DBI;
- sub new{
- $self={};
- $self->{select_db}=undef;
- $self->{delete_db}=undef;
- $self->{insert_db}=undef;
- $self->{update_db}=undef;
- bless $self;
- return $self;
- }
- sub connect_db{
- my $self=shift;
- if(@_){
- $self->{'connect_db'}=DBI->connect("DBI:mysql:database=@_[0];host=@_[1]","@_[2]","@_[3]") or die "No:$!\n";
- }
- return $self->{'connect_db'};
- }
- sub select_db{
- my $self=shift;
- if(@_){
- my $select=@_[0]->prepare(@_[1]);
- $select->execute();
- $self{select_db}=$select;
- }
- return $self{select_db};
- @_[0]->disconnect;
- }
- sub update_db{
- my $self=shift;
- if(@_){
- eval{
- $self->{update_db}=@_[0]->do(@_[1]);
- } or die "No\n";
- }
- }
- sub insert_db{
- my $self=shift;
- if(@_){
- eval{
- $self->{insert_db}=@_[0]->do(@_[1]);
- } or die "No\n";
- }
- }
- sub delete_db{
- my $self=shift;
- if(@_){
- eval{
- $self->{delete_db}=@_[0]->do(@_[1]);
- } or die "No\n";
- }
- }
- 1;
复制代码 先看代码,具体如下:- #!/usr/bin/perl
- use TDmodule;
- # create object
- $test=TDmodule->new();
- # connect db return config
- $config=$test->connect_db("3d_database","localhost","root","mojige123");
- # select for db return database
- $old=$test->select_db($config,"select * from old_papar");
- $user=$test->select_db($config,"select * from user_papar");
- sub result{
- local($sql)=shift;
- local($task)=shift;
- # print execute result
- while($list=$sql->fetchrow_hashref()){
- push(@target,$list->{$task});
- }
- return @target;
- }
- @old_papar=result($old,'id');
- @user_papar=result($user,'number');
- foreach my $a (@old_papar){
- print "$a\n";
- }
- print "--------------\n";
- foreach my $b (@user_papar){
- print "$b\n";
- }
复制代码 在这种情况下读出的数据会有重复读取的问题,例如目标数据要求是每个表读取一次,但是这个方法看起来是读取一次,实际上是读取了两次。具体结果如下所示:- root@crunchbang:~# perl TDmodule.pl
- 2
- 4
- 6
- 8
- 10
- --------------
- 2
- 4
- 6
- 8
- 10
- 145
- 693
- 168
- 746
- 206
- 319
复制代码 第一次的结果将会包含到第二次中,为了解决这个问题,我仔细的修改了下代码,发现,只需要每次将容器清空,即可。在这分享一下。。。- #!/usr/bin/perl
- use TDmodule;
- # create object
- $test=TDmodule->new();
- # connect db return config
- $config=$test->connect_db("3d_database","localhost","root","mojige123");
- # select for db return database
- $old=$test->select_db($config,"select * from old_papar");
- $user=$test->select_db($config,"select * from user_papar");
- sub result{
- local($sql)=shift;
- local($task)=shift;
-
- # clean list array
- @target=();
- # print execute result
- while($list=$sql->fetchrow_hashref()){
- push(@target,$list->{$task});
- }
- return @target;
- }
- @old_papar=result($old,'id');
- @user_papar=result($user,'number');
- foreach my $a (@old_papar){
- print "$a\n";
- }
- print "--------------\n";
- foreach my $b (@user_papar){
- print "$b\n";
- }
复制代码 |
|