gpt4 book ai didi

mysql - Perl 数据库交互

转载 作者:行者123 更新时间:2023-11-29 08:09:23 25 4
gpt4 key购买 nike

我刚刚开始使用 Perl。我能够使用 Perl 脚本连接到 MySQL 数据库、创建表并获取查询结果。我遇到一个任务,其中涉及“您必须使用提供的 DB.pm 进行所有数据库交互,并且必须按原样使用它(除了连接设置之外,不能修改 DB.pm)”。 这意味着什么?任何人都可以引导我走向正确的方向吗?

DB.pm 文件包含以下代码

package GUI::DB;

use strict;
use DBI;

use vars qw(@ISA @EXPORT);
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(dbConnect query);

#
# dbConnect - connect to the database, get the database handle
#
sub dbConnect {

# Read database settings from config file:
my $dsn = "DBI:mysql:database=test";
my $dbh = DBI->connect( $dsn,
'',
'',
{ RaiseError => 1 }
);

return $dbh;

}

#
# query - execute a query with parameters
# query($dbh, $sql, @bindValues)
#
sub query {
my $dbh = shift;
my $sql = shift;
my @bindValues = @_; # 0 or several parameters

my @returnData = ();

# issue query
my $sth = $dbh->prepare($sql);

if ( @bindValues ) {
$sth->execute(@bindValues);
} else {
$sth->execute();
}

if ( $sql =~ m/^select/i ) {
while ( my $row = $sth->fetchrow_hashref ) {
push @returnData, $row;
}
}

# finish the sql statement
$sth->finish();

return @returnData;
}

__END__
<小时/>

最佳答案

这可能意味着,在您的代码中您必须使用如下内容:

use GUI::DB;

my $dbh = dbConnect();
my $sql = qq{SELECT * FROM my_table};
my @data = query($sql, $dbh);

您通过提供的模块与数据库交互。

关于mysql - Perl 数据库交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com