我们使用dbi之前首先需要声明:
#!/usr/bin/perl -w
use dbi;
我们有两种方法可以建立perl与数据库之间的连接:
#!/usr/bin/perl -w
use dbi;
#建立与数据库的连接,第4个参数标明数据库类型
$dbh = dbi->connect( connection_string, username, password, msql );
if ( !defined $dbh ) {
die "cannot do \$dbh->connect: $dbi::errstr\n";
}
通过这种方法,返回一个数据库句柄。这是一种常用的用法,另外一种方法返回“驱动程序句柄”:
#!/usr/bin/perl -w
use dbi;
$drh = dbi->install_driver( msql );
if ( !defined $drh ) {
die "cannot load driver: $!\n";
}
这种方法多用来检查是否系统中是否存在某种驱动程序。
以下是一些利用dbi处理数据库的历程:
1、打开连接(数据库)已经关闭
#!/usr/bin/perl -w
#
# (c)1996 alligator descartes <descarte@hermetica.com>
#
# inout.pl: connects and disconnects from a specified database
use dbi;
if ( $#argv < 0 ) {
die "usage: inout.pl <database string> <database vendor>\n";
}
# create new database handle. if we cant connect, die()
$dbh = dbi->connect( , $argv[0], , $argv[1] );
if ( !defined $dbh ) {
die "cannot connect to msql server: $dbi::errstr\n";
}
# disconnect from the database
$dbh->disconnect;
exit;