Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359294
  • 博文数量: 35
  • 博客积分: 2176
  • 博客等级: 大尉
  • 技术积分: 797
  • 用 户 组: 普通用户
  • 注册时间: 2006-08-13 14:03
文章分类

全部博文(35)

文章存档

2012年(9)

2009年(14)

2008年(12)

我的朋友

分类:

2008-06-30 14:52:02

因为经常要连接数据库,当然写的包比较好用点,固定的不固定的数据库都可行,也方便下使用:写的这种方式主要是针对Mysql的,其它的不针对,当然要是没看仔细去用,肯定会出大问题,回头还得说我定的根本不能用。

#!F:/Perl/bin/perl.exe -w


package WebDB;

use strict;
use warnings;

use DBI;

my $host_name = "localhost";
my $db_name = "webdb";
my $dsn = "DBI:mysql:$db_name:$host_name";

sub connect
{
    return (DBI->connect ($dsn, "webdev", "webdev",
     {PrintError => 0, RaiseError => 1}))
        or die "Cannot connect to server: $DBI::errstr ($DBI::err)\n";
}
sub connect_newdb
{
    my ($dsn_new, $user, $passwd) = @_;
    
    return (DBI->connect ($dsn_new, $user, $passwd,
     {PrintError => 0, RaiseError => 1}))
        or die "Cannot connect to server: $DBI::errstr ($DBI::err)\n";
}

sub connect_with_option_file
{
    $dsn .= qq{;mysql_read_default_file=$ENV{HOME}/.my.cnf};
    return (DBI->connect ($dsn, undef, undef,
     {PrintError => 0, RaiseError =>1}));
}

sub change_database
{
    my ($dbh, $db_name) = @_;
    my ($old_pe, $old_re);
    my $result;
    
    $old_pe = $dbh->{PrintError}; # save current attribute values

    $old_re = $dbh->{RaiseError};
    $dbh->{PrintError} = 0; # disable both attributes

    $dbh->{RaiseError} = 0;
    $result = $dbh->do ("USE $db_name");
    $dbh->{PrintError} = $old_pe; # restore attribute values

    $dbh->{RaiseError} = $old_re;
    return (defined ($result)); # return true if USE succeeded

}

1;

怎么用,那就不说了吧,没必要。
阅读(1627) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~