Perl DBI (Database Interface) 提供統一的資料庫訪問介面,配合 DBD::mysql 驅動即可操作 MySQL。本文涵蓋模塊依賴、CPAN 安裝流程、基礎 CRUD、DBD::Proxy 遠程代理模式、錯誤處理最佳實踐。
DBI (核心介面)
├── DBD::mysql (MySQL 驅動) ← Msql-Mysql-modules 包含
├── DBD::Proxy (代理客戶端)
│ ├── RPC::PlClient
│ │ └── RPC::PlServer
│ │ └── Net::Daemon
│ └── Storable (序列化)
├── Data::ShowTable (結果美化輸出)
└── Data::Dumper (調試輸出)
# 1. 安裝基礎依賴 (按順序)
cpanm Net::Daemon Storable RPC::PlClient RPC::PlServer
# 2. 安裝 DBI 核心
cpanm DBI
# 3. 安裝 MySQL 驅動 (含 DBD::mysql)
cpanm DBD::mysql
# 4. 輔助模塊
cpanm Data::ShowTable Data::Dumper
# 5. 驗證
perl -MDBI -MDBD::mysql -e 'print "OK\n"'
perl -MDBI -e 'print join "\n", DBI->available_drivers()'
注意: Data::ShowTable 的 Makefile.PL 可能需手動補上 =head1 SYNOPSIS 後再 make install。
#!/usr/bin/perl
use strict; use warnings;
use DBI;
use Data::ShowTable;
# 連接配置
my $dsn = "DBI:mysql:database=abacus;host=mysql.example.com;port=3306;mysql_enable_utf8=1";
my $user = "app_user";
my $pass = "secure_pass";
# 建立連接 (RaiseError 自動拋出異常)
my $dbh = DBI->connect($dsn, $user, $pass, {
RaiseError => 1,
PrintError => 0,
AutoCommit => 1,
mysql_auto_reconnect => 1,
}) or die "Connect failed: $DBI::errstr";
# 查詢所有表
my $sth = $dbh->prepare("SHOW TABLES");
$sth->execute();
print "Tables in abacus:\n";
ShowTable(
'titles' => ['Table_Name'],
'rows' => sub { $sth->fetchrow_arrayref() },
'fmt' => 'html', # 或 'box', 'list', 'simple'
);
$sth->finish();
$dbh->disconnect();
# 預處理防注入
my $sth = $dbh->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$sth->execute('Li Si', 'li@example.com');
my $id = $dbh->last_insert_id(undef, undef, undef, undef);
# 事務控制
eval {
$dbh->begin_work();
$dbh->do("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
$dbh->do("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
$dbh->commit();
};
if ($@) {
warn "Transaction failed: $@";
$dbh->rollback();
}
# 錯誤代碼檢查 (如重複鍵 1062)
if ($dbh->err == 1062) { ... }
#!/usr/bin/perl
use DBI;
use RPC::PlServer;
use Net::Daemon;
my $server = RPC::PlServer->new(
'port' => 3333,
'access' => ['allow 10.0.0.0/8'], # 限制客戶端 IP
'user' => 'dbproxy',
'password' => 'proxy_pass',
);
$server->Bind('DBI', 'DBI:mysql:database=abacus;host=localhost');
$server->Run();
my $dsn = "DBI:Proxy:hostname=db-proxy-host;port=3333;dsn=DBI:mysql:abacus";
my $dbh = DBI->connect($dsn, 'dbproxy', 'proxy_pass', { RaiseError => 1 });
# 後續操作與本地連接完全一致
Perl + DBI + DBD::mysql 是成熟、穩定、高效的組合。掌握模塊安裝順序、RaiseError 異常模式、預處理、事務 eval 塊、Proxy 代理架構,即可應對從腳本自動化到企業級應用的各類場景。現代新專案亦可考慮 DBIx::Class ORM 進一步提升開發效率。