cpan DBI DBD::mysql
# 或系統包管理器
yum install perl-DBI perl-DBD-MySQL
use strict;
use warnings;
use DBI;
# 1. 連線 (RaiseError=1 異常即拋出,無需手動判斷)
my $dsn = "DBI:mysql:database=my_db;host=127.0.0.1;port=3306;mysql_enable_utf8=1";
my $dbh = DBI->connect($dsn, 'user', 'pass', {
RaiseError => 1,
PrintError => 0,
AutoCommit => 1, # 手動事務時設 0
mysql_auto_reconnect => 1,
});
# 2. 插入並取得自增 ID
my $sth = $dbh->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$sth->execute('Alice', 'alice@example.com');
my $new_id = $dbh->{mysql_insertid}; # 或 $dbh->last_insert_id(undef,undef,undef,undef)
$sth->finish();
# 3. 批量插入 (事務包裹)
$dbh->begin_work;
eval {
my $sth_batch = $dbh->prepare("INSERT INTO logs (msg) VALUES (?)");
for my $msg (@messages) {
$sth_batch->execute($msg);
}
$dbh->commit;
$sth_batch->finish();
};
if ($@) { $dbh->rollback; die "Batch insert failed: $@"; }
# 4. 查詢 - 逐行處理 (大結果集節省記憶體)
my $sth_sel = $dbh->prepare("SELECT id, name FROM users WHERE status = ?");
$sth_sel->execute('active');
while (my $row = $sth_sel->fetchrow_hashref) {
printf "ID: %d, Name: %s\n", $row->{id}, $row->{name};
}
$sth_sel->finish();
# 5. 查詢 - 一次性取回 (小結果集)
my $rows = $dbh->selectall_arrayref("SELECT * FROM config", { Slice => {} });
for my $r (@$rows) { ... }
# 6. 更新/刪除
my $affected = $dbh->do("UPDATE users SET last_login=NOW() WHERE id=?", undef, $uid);
# 7. 斷開
$dbh->disconnect();
| 需求 | 實現 |
|---|---|
| 預處理緩存 | prepare_cached 自動緩存 Statement Handle,高頻 SQL 必用 |
置換 NULL 為預設值 | SQL 中用 COALESCE(col, 'default') 或 Perl 端 $val // 'default' |
| 連線池 (持久化) | Apache mod_perl + Apache::DBI;獨立腳本用 DBI->connect(..., { dbi_connect_method => 'connect_cached' }) |
| 錯誤碼處理 | $dbh->err / $dbh->errstr;RaiseError=1 時直接 eval { } 捕獲 |
| 多結果集 | do { while($sth->fetch) {...} } while($sth->{more_results}); |
mysql_enable_utf8=1 (DBD::mysql 4.04+),或執行 SET NAMES utf8mb4。$dbh->{mysql_insertid} 僅在 AutoCommit=1 或事務提交後有效;事務中需用 last_insert_id。mysql_auto_reconnect=1 並設置 wait_timeout 配合應用端心跳。Perl DBI + DBD::mysql 是成熟穩定的組合,核心模式為 connect → prepare → execute → fetch/do → finish → disconnect。善用 prepare_cached、RaiseError、begin_work/commit/rollback 三大機制,即可寫出健壯、高效的資料庫交互代碼。