3

我在使用 DBI 模块连接到我的数据库时遇到了一些麻烦。我有一个属性文件,其中指定我是否要通过简单的database=oracledatabase=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 条件的一部分时,我可以很好地连接到任何一个数据库,任何想法为什么它现在会导致错误?

4

2 回答 2

4

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

my $dbh;

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

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

进一步阅读:

于 2012-07-16T17:09:41.373 回答
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},
);
于 2012-07-16T17:34:59.197 回答