I handled this once by having the module create and tear down the db handle, via BEGIN and END clauses, and when I needed the use the handle directly in my main script, I simply used something like this:

package My::Module; my $db; BEGIN { $db = DBI->connect($blah, $blah, $blah) or die "...\n"; } END { $db and $db->disconnect; } sub db { $db; }

Which meant that I could grab the handle whenever I needed to do some ad-hoc querying, and have the module take care of the fiddly bits, as well as all the standard db stuff it was supposed to do anyway, all nicely encapsulated. You can actually do what appears to be rather weird...

my $ss = My::Module::db->prepare($sql);

I.e., nary a scalar in sight, but it does what you expect, without having to explicitly save the $db reference in a scalar. It's not exactly walking into some-one's living room without being invited, but it's close to leaning on the window sill and watching the TV set.

I'm not sure I'd do this in a codebase with multiple people, but it worked well enough for me.

--
g r i n d e r

In reply to Re: Using a single DBI handle in a script and a module by grinder
in thread Using a single DBI handle in a script and a module by George_Sherston

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.