Perl数据库连接在.pm文件中不起作用

时间:2018-08-31 05:37:27

标签: mysql perl soap dbi

在Perl中,我已经使用DBI概念连接了数据库。数据库连接和选择表查询在.pl文件中工作正常。但是我已经在.pm文件中运行了DBI数据库连接代码。它不起作用。

请查看代码。

Sample.pl(工作正常)

use DBI;
my $driver = "mysql"; 
    my $database = "marketplace_perl";
    my $dsn = "DBI:$driver:database=$database";
    my $userid = "root";
    my $password = "root";
    my $dbh = DBI->connect($dsn, $userid, $password );
    my $dbh=connect_db();
        my $sth = $dbh->prepare("SELECT UserEmail,UserPassword FROM pj_user where UserEmail=? and UserPassword=?");

        $sth->execute($UserEmail,$UserPassword);

Marketplace.pm(不起作用)

package Marketplace;
use DBI;
    sub connect_db {
        my $driver = "mysql"; 
        my $database = "marketplace_perl";
        my $dsn = "DBI:$driver:database=$database";
        my $userid = "root";
        my $password = "root";
        my $dbh = DBI->connect($dsn, $userid, $password );
       return $dbh;
    }

    sub login_marketplace { 

    my $dbh=connect_db();
            my $sth = $dbh->prepare("SELECT UserEmail,UserPassword FROM pj_user where UserEmail=? and UserPassword=?");

            $sth->execute($UserEmail,$UserPassword);
            my $User_count=$sth->rows;
    return $User_count

    }

它返回错误消息“无法访问类(市场):无法在@INC中找到DBI.pm(您可能需要安装DBI模块)”

请让我知道如何解决数据库问题。

1 个答案:

答案 0 :(得分:1)

请尝试在marketplace.pm文件中的以下代码。

use ENV;
my $PERL5LIB= $ENV{'PERL5LIB'};
 package Marketplace;

BEGIN {
 push(@INC, $PERL5LIB);
};
use DBI;
sub connect_db {
my $driver = "mysql"; 
my $database = "marketplace_perl";
my $dsn = "DBI:$driver:database=$database";
my $userid = "root";
my $password = "root";
my $dbh = DBI->connect($dsn, $userid, $password );
return $dbh;
}

sub login_marketplace { 

my $dbh=connect_db();
my $sth = $dbh->prepare("SELECT UserEmail,UserPassword FROM pj_user where UserEmail=? and UserPassword=?");

$sth->execute($UserEmail,$UserPassword);
my $User_count=$sth->rows;
return $User_count

}