萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

Perl 操作 MySQL 資料庫標準流程:DBI 連線、準備語句、執行、取回自增 ID、抓取結果集

完整範例

use DBI;
use strict;
use warnings;

# 1. 連線 (RaiseError 自動拋出異常)
my $dbh = DBI->connect(
    "DBI:mysql:database=DBname;host=localhost",
    "user", "pwd",
    { RaiseError => 1, AutoCommit => 1, mysql_enable_utf8 => 1 }
);

# 2. 準備語句 (參數化,防注入)
my $sth = $dbh->prepare(
    "INSERT INTO table_name (Name, region_id, inuse, url) VALUES (?, ?, 1, ?)"
);

# 3. 執行插入
$sth->execute($r_name, $t+1, $r_url);

# 4. 取得自增 ID
my $table_key = $dbh->{mysql_insertid};
print "Inserted ID: $table_key\n";

# 5. 查詢並逐行處理
$sth = $dbh->prepare("SELECT id, name FROM table_name WHERE region_id = ?");
$sth->execute($t+1);
while (my $row = $sth->fetchrow_arrayref) {
    printf "ID: %s, Name: %s\n", $row->[0], $row->[1];
}

# 6. 關閉
$sth->finish();
$dbh->disconnect();

關鍵點

  • RaiseError => 1:例外自動 die,省去手動檢查 $DBI::errstr。
  • mysql_enable_utf8 => 1:自動處理 UTF-8 編碼 (DBD::mysql 4.04+)。
  • 佔位符 ? + execute(@params) 實現參數化查詢。
  • $dbh->{mysql_insertid} 取得最後 AUTO_INCREMENT 值。
  • fetchrow_arrayref 回傳陣列參考,fetchrow_hashref 回傳雜湊參考 (欄位名為鍵)。
copyright © 萬盛學電腦網 all rights reserved