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();
 _  _ _  _  
(_|| | |(_|><
 _|   

In reply to Re: Passing Database handles to other modules. by gmax
in thread Passing Database handles to other modules. by thunders

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.