in reply to Problem managing persistent database connections in modules
package myFoo; use strict; use warnings; use dbConnection; sub new { my $self = bless( {}, shift ); $self->{id} = shift; my $db = new dbConnection(); # # build sql # load from $db # }
# # this is not my production code... i had to chop it down significantl +y to for the purpose of this example # although i welcome comments/suggestions! # package dbConnection; use strict; use warnings; use Win32::ODBC; my %_ConnectionPools; my $_DefaultConnectionString; sub DefaultConnectionString { @_ ? $_DefaultConnectionString = shift : $_DefaultConnectionString; } sub _PoolConnection { my $poolname = shift; my $connection = shift; my $pool = _GetPool($poolname); push @$pool,$connection; } sub _GetPool { my $poolname = shift; my $pool = $_ConnectionPools{$poolname}; if (!defined $pool) { my @connections; $pool = \@connections; $_ConnectionPools{$poolname} = $pool; } return $pool; } sub new { my $self = bless( {}, shift ); $self->{_ConnectionString} = shift; # # check if any connection exist in pool # my $pool = _GetPool( $self->{_ConnectionString} ); my $connection = shift @$pool; if ( ! $connection ) { # # no connection exists, create new connection # $connection = new Win32::ODBC( $self->{_ConnectionString} ); if ( ! $connection ) { die "Could not connect to [" . $self->{_ConnectionString} +. "]"; } } $self->{_Connection} = $connection; return $self; } sub DESTROY { my $self = shift; _PoolConnection($self->{_ConnectionString}, $self->{_Connection} ) +; $self->{_Connection} = 0; } 1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Problem managing persistent database connections in modules
by mp (Deacon) on Jul 26, 2002 at 00:35 UTC |