有条件地连接到数据库

时间:2012-07-16 17:05:23

标签: perl if-statement dbi

使用DBI模块连接数据库时遇到了一些麻烦。我有一个属性文件,并在其中指定是否要通过简单的database=oracledatabase=postgres连接到我的oracle或postgres数据库。我的属性文件是使用Config :: Tiny模块设置的,我的变量设置如下:

my $database = $config->{myDB}->{database};
                       ...

我不明白的是即使这适用于我的所有变量,如果我尝试连接到属性文件中指定的任何数据库...

if($database eq "oracle"){
    my $dbh = DBI->connect("dbi:Oracle:host=abc123-server;sid=XE;port=1521","User","Pass");
}
elsif($database eq "postgres"){
    my $dbh = DBI->connect("dbi:Pg:dbname=pepperoni;host=789xyz-server;port=5444;","Foo","Bar");
}else{
    print "Could not connect to a database";
}

......我最终遇到了这些错误:

Global symbol "$dbh" requires explicit package name at supportvuloop.pl line 70.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 80.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 81.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 82.
Global symbol "$dbh" requires explicit package name at reportloop.pl line 88.

我可以连接到任何一个数据库,只要它们不属于if条件,任何想法为什么它会导致错误?

2 个答案:

答案 0 :(得分:4)

您的$ dbh变量未在正确的范围内声明。您应该在“if”语句之前声明它:

my $dbh;

if ($x) {
    $dbh=xxx1;
} elsif ($y) {
    $dbh=xxx2;
} else { # error
}
...

他们的代码是结构化的,$dbh变量在“if”块中被声明为my(并且独立地,在“else”块内),因此其余的代码没有看到那些变量

进一步阅读:

答案 1 :(得分:3)

DVK已经回答了你的问题,但我想提一个小费。我会按如下方式编写代码,因为它将配置与数据库连接分开:

my %connect_info = (
   "oracle" => {
      dsn      => "dbi:Oracle:host=abc123-server;sid=XE;port=1521",
      user     => "User",
      password => "Pass",
   },
   "postgres" => {
      dsn      => "dbi:Pg:dbname=pepperoni;host=789xyz-server;port=5444;",
      user     => "Foo",
      password => "Bar",
   },
);

my $connect_info = $connect_info{$database}
   or die("Unknown database $database\n");

my $dbh = DBI->connect(
   $connect_info{dsn},
   $connect_info{user},
   $connect_info{password},
);