学习Perl DBI -- 连接到数据库

    从data_sources函数知道了连接信息的格式后, 我们就可以连接了, 只要调用DBI的connect函数, 根据连接信息的格式, 可以自动区别数据库类型, 选择合适的数据库驱动进行连接. 一般写法如下:

my $dbh = DBI->connect("data source", "username", "password");
my $dbh = DBI->connect("data source", "username", "password", properties);

    connect函数如果连接失败会返回undef值, 因此很容易判断连接是否成功:

my $dbh = DBI->connect("dbi:Oracle:test8i","anysql", "anysql")
            || die("Cannot connect to database!\n");

my $dbh = DBI->connect("dbi:Oracle:test8i","anysql", "anysql");

if (!defined($dbh)
{
   ...
}

    连接属性常用的有两个: RaiseError和PrintError. RaiseError如果设为1时, 如果DBI调用遇到错误, 将引起程序退出, 设为0时遇到错误后将继续执行后续的代码. PrintError如果设为1时则遇到错误时打印错误信息, 设为0时则不打印错误信息. 那么如何在程序中获得错误信息呢? 可以通过DBI中的变量或连接对象的几函数来获得:

my $dbh = DBI->connect("dbi:Oracle:test8i","anysql", "anysql",
            {RaiseError=0,PrintError=0,});
......
my $errcode = $DBI::err;
my $errmsg  = $DBI::errstr;
my $errcode = $dbh->err();
my $errmsg  = $dbh->errstr();

    在程序中你可以随时更改PrintError和RaiseError的设定, 如下所示:

$dbh->{PrintError} = ...;
$dbh->{RaiseError} = ...;

    对于连接到Oracle这样的数据库时, 如果你不想再和数据库打交道了, 最好还是在代码中切断连接, 并在连接之前发一个commit或rollback(根据你的需要), 如下所示:

$dbh->commit();
$dbh->rollback();
$dbh->disconnect();

    这一部分其实还是比较复杂的, 在这儿就写得太简单了.

发表留言:

« Previous | Main | Next »

英语900句 | English 900

  • Witch pleasure.
  • 很高兴.
  • I'm sorry. I'm engaged now.
  • 对不起, 我现在正忙着.
  • I'm glad to, but I'm afraid I don't have the time.
  • 我很乐意, 但我恐怕没时间.
  • Would you mind closing the window for me?
  • 能帮我关一下窗户吗? (你介意关下窗户吗? )
  • Not at all.
  • 当然可以. (当然不介意)