在Perl中進行數據庫連接和操作通常需要使用DBI(數據庫接口)模塊,以下是一個簡單的示例:
use DBI;
my $db_name = "database_name";
my $db_user = "username";
my $db_pass = "password";
my $dsn = "DBI:mysql:$db_name";
my $dbh = DBI->connect($dsn, $db_user, $db_pass) or die "Cannot connect to database: $DBI::errstr";
# 執行SQL查詢
my $sql = "SELECT * FROM table_name";
my $sth = $dbh->prepare($sql);
$sth->execute();
# 獲取查詢結果
while (my @row = $sth->fetchrow_array()) {
print join(", ", @row) . "\n";
}
# 關閉數據庫連接
$sth->finish();
$dbh->disconnect();
在上面的示例中,我們首先使用DBI
模塊建立數據庫連接,然后執行一個簡單的SQL查詢,并打印查詢結果。最后,我們關閉了數據庫連接。您可以根據實際情況修改數據庫連接信息和SQL查詢語句。