Depends on how much opening and closing of the database there would be on the present typical execution and how long your application is open versus how long you actually need the database open (I usually find that database operations are the slowest part of an application, so you may as well keep a connection open). But one possibility is to have one module actually open and close the database, and and have the rest of the modules use that module's db handle.

Have every module do a 'my $dbh = MyDBI->connect(...)' and in your MyDBI module, the first call actually connects while subsequent calls just reuse the same handle (stored perhaps in a package global variable).

The disconnect would have to be at the end of the application I suppose.

Update: I take it all (well, most of it) back. Use connect_cached() and just let every module connect, just don't disconnect until the end of the app.

Another update:Looking at the docs for connect_cached(), I'm not sure the author really recommends it, so maybe my first suggestion is the way to go for production code.


In reply to Re: Using DBI handle in several packages by runrig
in thread Using DBI handle in several packages by Beatnik

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.