在Perl中與數(shù)據(jù)庫(kù)進(jìn)行交互通常使用DBI模塊,以下是一個(gè)簡(jiǎn)單的Perl代碼示例,連接到MySQL數(shù)據(jù)庫(kù)并查詢數(shù)據(jù):
use DBI;
# 數(shù)據(jù)庫(kù)信息
my $database = "database_name";
my $host = "localhost";
my $port = "3306";
my $user = "username";
my $password = "password";
# 連接到數(shù)據(jù)庫(kù)
my $dbh = DBI->connect("DBI:mysql:database=$database;host=$host;port=$port", $user, $password)
or die "無(wú)法連接到數(shù)據(jù)庫(kù): $DBI::errstr";
# 準(zhǔn)備查詢語(yǔ)句
my $sql = "SELECT * FROM table_name";
my $sth = $dbh->prepare($sql);
# 執(zhí)行查詢
$sth->execute();
# 獲取查詢結(jié)果
while (my @row = $sth->fetchrow_array()) {
print join(", ", @row) . "\n";
}
# 斷開與數(shù)據(jù)庫(kù)的連接
$dbh->disconnect();
在上面的代碼中,我們首先使用DBI模塊連接到數(shù)據(jù)庫(kù),然后準(zhǔn)備查詢語(yǔ)句并執(zhí)行查詢,最后遍歷查詢結(jié)果并輸出。最后,我們斷開與數(shù)據(jù)庫(kù)的連接。您可以根據(jù)自己的需求修改查詢語(yǔ)句和數(shù)據(jù)庫(kù)信息。