读完本文之後,咱们就能学到利用 DBI 创建一个完备的资料库程式。 如下就先由 DBI 的基本功能 开始,然後再逐步研究改善效能与可靠度技巧。架构
基本功能函数
localhost:~/DBI-1.08$ perl Makefile.PL && make xml
&& make test && make install ci
在 DBI 与 DBD 安装完成之後, 您能够执行下列指令阅读更多的资讯: hash
每一种资料库都有不一样的连线方式, 如果想知道特殊用法, 请务必阅读 DBD 所提供的说明文 件。 下面的例子是连线到 DBMaker 的基本方法.
my $dbh = DBI->connect( 'dbi:DBMaker:dbsample',
my $dbh = DBI->connect( 'dbi:DBMaker:dbsample',
|| die "Database connection not made: $DBI::errstr";
在下一段程式中,是但愿进行采交易处理的用法,设定成 AutoCommit off,RaiseError on,而 让 PrintError 使用内定值 on.
my $dbh = DBI->connect( 'dbi:DBMaker:dbsample',
|| die "Database connection not made: $DBI::errstr";
有一点要特别注意,若是资料库自己不支援交易处理的功能时,设定 AutoCommit off 会接收到错 误发生的传回值.
my $dbh = DBI->connect( 'dbi:DBMaker:dbsample',
|| die "Database connection not made: $DBI::errstr";
[ 0, "Larry Wall", "Perl Author", "555-0101" ],
[ 1, "Tim Bunce", "DBI Author", "555-0202" ],
[ 2, "Randal Schwartz", "Guy at Large", "555-0303" ],
[ 3, "Doug MacEachern", "Apache Man", "555-0404" ]
my $sql = qq{ INSERT INTO employees VALUES ( ?, ?, ?, ? ) };
my $sth = $dbh->prepare( $sql );
$sth->bind_param( 1, @$_->[0]);
$sth->bind_param( 2, @$_->[1]);
$sth->bind_param( 3, @$_->[2]);
$sth->bind_param( 4, @$_->[3]);
warn "Database error: $DBI::errstr/n";
$dbh->rollback(); #just die if rollback is failing
关於 finish 的呼叫在咱们的例子并非必要的. 这个函数适用於 statement handle 完成时所使 用。
仔细阅读 Perl DBI manual 以深刻解 DBI 架构
DBI - A Database Interface Module for Perl 5