perl数据库连接在.pm文件中不工作

5jdjgkvh  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(331)

在perl中,我使用dbi概念连接了数据库。数据库连接和select表查询在.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

    }

它返回错误消息“failed to access class(marketplace):can't locate dbi.pm in@inc(you may need to install the dbi module)”
请让我知道如何解决数据库问题。

hwazgwia

hwazgwia1#

在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

}

相关问题