Board logo

标题: 建立与数据库的连接 [打印本页]

作者: cnangel    时间: 2005-8-25 19:38     标题: 建立与数据库的连接

作者:小歪歪
email: annysun@163.net
日期:2000-07-14 14:26:42

我们使用DBI之前首先需要声明:
  1. #!/usr/bin/perl -w
  2. use DBI;
复制代码
我们有两种方法可以建立PERL与数据库之间的连接:
  1. #!/usr/bin/perl -w
  2. use DBI;
  3. #建立与数据库的连接,第4个参数标明数据库类型
  4. $dbh = DBI->connect( ';connection_string';, ';username';, ';password';, ';mSQL'; );
  5. if ( !defined $dbh ) {
  6. die "Cannot do \$dbh->connect: $DBI::errstr\n";
  7. }
复制代码
通过这种方法,返回一个数据库句柄。这是一种常用的用法,另外一种方法返回“驱动程序句柄”:
  1. #!/usr/bin/perl -w
  2. use DBI;
  3. $drh = DBI->install_driver( ';mSQL'; );
  4. if ( !defined $drh ) {
  5. die "Cannot load driver: $!\n";
  6. }
复制代码
这种方法多用来检查是否系统中是否存在某种驱动程序。
以下是一些利用DBI处理数据库的历程:
1、打开连接(数据库)已经关闭
  1. #!/usr/bin/perl -w
  2. #
  3. &#35; (c)1996 Alligator Descartes <descarte@hermetica.com>
  4. &#35;
  5. &#35; inout.pl: Connects and disconnects from a specified database
  6. use DBI;
  7. if ( &#36;&#35;ARGV < 0 ) {
  8. die "Usage: inout.pl <Database String> <Database Vendor>\n";
  9. }
  10. &#35; Create new database handle. If we can';t connect, die()
  11. &#36;dbh = DBI->connect( ';';, &#36;ARGV[0], ';';, &#36;ARGV[1] );
  12. if ( !defined &#36;dbh ) {
  13. die "Cannot connect to mSQL server: &#36;DBI::errstr\n";
  14. }
  15. &#35; Disconnect from the database
  16. &#36;dbh->disconnect;
  17. exit;
复制代码





欢迎光临 星星博客 (http://bbs.huhoo.net/) Powered by Discuz! 7.0.0