因为经常要连接数据库,当然写的包比较好用点,固定的不固定的数据库都可行,也方便下使用:写的这种方式主要是针对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;
|
怎么用,那就不说了吧,没必要。
阅读(1659) | 评论(0) | 转发(0) |