首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

Perl DBI 操作 MySQL 速查手冊:連線、增刪改查、事務與錯誤處理

     編輯:MySQL 資料庫相關知識

前置準備

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});

常見坑位

  • 編碼亂碼:DSN 必帶 mysql_enable_utf8=1 (DBD::mysql 4.04+),或執行 SET NAMES utf8mb4。
  • 自增 ID 取錯:$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 三大機制,即可寫出健壯、高效的資料庫交互代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved