Perl 連接 MySQL 完整實戰指南
透過 Perl DBI (Database Interface) 模組,可輕鬆實現 MySQL 的連線、查詢、插入、更新等操作。本文提供可直接執行的完整範例代碼。
環境準備
# 安裝 DBI 與 MySQL 驅動
cpan DBI
cpan DBD::mysql
# 或系統包管理器
apt-get install libdbi-perl libdbd-mysql-perl # Debian/Ubuntu
yum install perl-DBI perl-DBD-MySQL # CentOS/RHEL
完整範例腳本
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
# 1. 連接資料庫
my $dsn = "DBI:mysql:database=eygle;host=localhost";
my $user = "username";
my $pass = "password";
my $dbh = DBI->connect($dsn, $user, $pass, {
RaiseError => 1, # 錯誤自動拋出異常
PrintError => 0, # 不自動打印警告
AutoCommit => 1, # 自動提交
mysql_enable_utf8 => 1 # UTF-8 支援
}) or die "連接失敗: $DBI::errstr";
print "資料庫連接成功\n";
# 2. 插入資料
my $rows = $dbh->do("INSERT INTO test (id, name) VALUES (1, 'eygle')");
print "插入行數: $rows\n";
# 3. 查詢資料(預處理語句,防注入)
my $sth = $dbh->prepare("SELECT name FROM test WHERE id = ?");
$sth->execute(1);
while (my $ref = $sth->fetchrow_hashref()) {
print "查詢結果: $ref->{name}\n";
}
$sth->finish();
# 4. 更新資料
$rows = $dbh->do("UPDATE test SET name = 'updated' WHERE id = 1");
print "更新行數: $rows\n";
# 5. 刪除資料
$rows = $dbh->do("DELETE FROM test WHERE id = 1");
print "刪除行數: $rows\n";
# 6. 斷開連接
$dbh->disconnect();
print "連接已關閉\n";
核心 API 對照表
| 方法 | 用途 | 回傳值 |
| DBI->connect() | 建立連接 | Database Handle ($dbh) |
| $dbh->do() | 執行非查詢 SQL (INSERT/UPDATE/DELETE/DDL) | 影響行數 |
| $dbh->prepare() | 預處理 SQL,返回 Statement Handle | Statement Handle ($sth) |
| $sth->execute() | 執行預處理語句(可綁定參數) | 成功真/失敗假 |
| $sth->fetchrow_hashref() | 取得下一行為 HashRef {欄位名=>值} | HashRef 或 undef |
| $sth->fetchrow_arrayref() | 取得下一行為 ArrayRef [值1, 值2...] | ArrayRef 或 undef |
| $sth->fetchall_arrayref() | 一次取得所有行 | ArrayRef of ArrayRefs |
| $dbh->last_insert_id() | 取得最後 AUTO_INCREMENT 值 | 整數 |
| $dbh->disconnect() | 關閉連接 | 布林值 |
最佳實踐要點
- 預處理語句: 所有含變數的 SQL 必須用
prepare() + execute(@params),防止 SQL 注入
- 錯誤處理: 連接參數設
RaiseError => 1,配合 eval { ... } 捕獲異常
- 交易控制:
$dbh->{AutoCommit} = 0 → 執行多條 SQL → $dbh->commit() / $dbh->rollback()
- 連接池: 長運行程式使用
DBI->connect_cached() 或 Apache::DBI (mod_perl 環境)
- 編碼: 連接參數加
mysql_enable_utf8 => 1,資料庫/表/連線三端統一 UTF-8
常見問題排查