Perl DBI 基本流程
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
# 1. 連線
my $dbh = DBI->connect(
"DBI:mysql:database=eygle;host=localhost",
"username", "password",
{ RaiseError => 1, PrintError => 0, AutoCommit => 1 }
) or die "連線失敗: $DBI::errstr";
# 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");
$sth->execute();
while (my $ref = $sth->fetchrow_hashref()) {
print $ref->{name} . "\n";
}
$sth->finish();
# 4. 斷線
$dbh->disconnect();
執行結果
$ perl test.pl
影響行數: 1
eygle
關鍵點說明
RaiseError => 1:發生錯誤自動 die,簡化錯誤處理
prepare() + execute():預處理陳述句,防止 SQL 注入
fetchrow_hashref():以欄位名為鍵回傳雜湊參考
- 記得
finish() 釋放陳述句資源,disconnect() 關閉連線
進階用法
- 交易控制:
$dbh->{AutoCommit} = 0; 後用 commit()/rollback()
- 預處理佔位符:
$dbh->prepare("INSERT INTO t (c) VALUES (?)") 配合 execute($val)
- 連線池:可搭配
DBIx::Connector 或 DBI::Pool