in reply to Passing Database handles to other modules.

You can pass an already initialized database handler, store it inside the object and then reuse it at will. Here's a tested example.

#!/usr/bin/perl -w use DBI; use strict; package Other; sub new { my $class = shift; my $self = bless {}, $class; my $dbh = shift || return undef; $self->{dbh} = $dbh; # store the dbh # for future use return $self; } sub do_it { my $self = shift; my $query = shift; # # reuses the stored dbh # my $sth= $self->{dbh}->prepare($query); $sth->execute; while (my $row = $sth->fetchrow_arrayref()) { print "@$row\n"; } } package main; sub do_it_differently { my $db = shift; my $query = shift; my $rows = $db->selectall_arrayref($query); for my $row (@$rows) { print "<@$row>\n"; } } my $dbh = DBI->connect("DBI:driver:database", # change it 'username', 'password', {RaiseError => 1}) or die "can't connect\n"; my $query = qq{select * from departments }; my $ext = new Other $dbh # passes a dbh to an object or die "can't create\n"; $ext->do_it($query); # calls a method that uses a stored +dbh do_it_differently ($dbh, $query); # passes a dbh to a sub $dbh->disconnect();
 _  _ _  _  
(_|| | |(_|><
 _|   

Replies are listed 'Best First'.
Re: Re: Passing Database handles to other modules.
by perrin (Chancellor) on May 06, 2003 at 17:31 UTC
    The only trouble with this approach is that in a mod_perl setting that object could exist for hours with no use, during which time that connection might time out. If you fetch your $dbh from Apache::DBI at least once per request, you will avoid this. Apache::DBI will notice that the connection is dead and reconnect.