Perl 数据查询的技术

今天测试查询数据的时候发现一个很奇异的问题,对着这个问题做了个研究。

先看代码,具体如下:

#!/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
";
}
print "--------------
";
foreach my $b (@user_papar){
   print "$b
";
}

在这种情况下读出的数据会有重复读取的问题,例如目标数据要求是每个表读取一次,但是这个方法看起来是读取一次,实际上是读取了两次。具体结果如下所示:

root@crunchbang:~# perl TDmodule.pl 
1
2
3
4
5
6
7
8
9
10
11
--------------
1
2
3
4
5
6
7
8
9
10
11
145
404
693
6
168
18
746
429
206
403
319

第一次的结果将会包含到第二次中,为了解决这个问题,我仔细的修改了下代码,发现,只需要每次将容器清空,即可。在此MARK一下。方便以后查询。

#!/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
";
}
print "--------------
";
foreach my $b (@user_papar){
   print "$b
";
}
原文地址:https://www.cnblogs.com/xiaoCon/p/3203617.html