17
十一
十一
connect, use, reference, and then, die, what about the mysql handler? Hang…
then, more and more mysql connect untill you can’t connect anymore….
in perl, you can use module’s DESTROY function to aotu close the dbh( the save when file handle).
ex.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package HiConnectDB; use DBI; sub new { my $class = shift; my ($dbname, $dbuser, $dbpass) = @_; $class = ref($class) || $class; my $self = bless {}, $class; $self->{'_dbh'} = DBI->connect("dbi:mysql:database=$dbname;host=localhost", $dbuser, $dbpass) or return undef; return $self; } sub DESTROY { shift()->{_dbh}->disconnect; $self->SUPER::DESTROY if $self->can("SUPER::DESTROY"); } 1; |
在主程序中使用上面的模块:
1 2 3 4 5 6 7 8 9 10 11 12 13 | sub myfun { use HiConnectDB; my $db = new HiConnect("dbname", "dbuser", "dbpass"); or die "Can't connect to db with (dbname, dbuser, xxxx)\n"; $dbh = $db->{_dbh}; $dbh->do("show tables") ### barbarbar, other work ### barbarbar, other work ### barbarbar, other work ### befor exit this route, $db is destroied, and dbh is closed. } |