I usually just write a little MyDB module that has one method: connect. Then any script that wants to use the database just does:

use MyDB; my $dbh = MyDB::connect();

This method will also let you add connection pooling later without changing any code other than the MyDB module.

Here's a sample MyDB module with a connect method that lets you override any of the default connect parameters (note: I just rewrote a good chunk of this as I posted it, and haven't tested it, so...):

package MyDB; use DBI; my %Default = ( database => 'mydatabase', driver => 'mysql', hostname => 'localhost', port => 3306, username => 'someuser', password => 'topsecret', options => { AutoCommit => 1, RaiseError => 0, } ); sub connect { my %params = @_; my $connect_str=sprintf("dbi:%s:database=%s;hostname=%s;port=%s", $params{driver} || $Default{driver}, $params{database} || $Default{database}, $params{hostname} || $Default{hostname}, $params{port} || $Default{port}); return DBI->connect($connect_str, $params{username} || $Default{username}, $params{password} || $Default{password}, $params{options} || $Default{options} ); } 1;

Brad


In reply to Re: Seeking efficient and safe way to store database connection information by bgreenlee
in thread Seeking efficient and safe way to store database connection information by kayak9630

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.