I've been writing a Perl app (part CGI, part back-end) with lots of SQL mixed in, and our project has pretty much settled into using straight DBI with a hash to contain all the prepared statements, like this:
use DBI;
use DBD::whatever; # I use Pg, you use MySQL, same idea
my $cn = DBI->connect( 'YOUR PARMS HERE' )
or die "Couldn't Connect!";
my %st;
$st{'GetThings'} = $cn->prepare(<<ENDSQL);
SELECT Thing_One, Thing_Two
FROM Things
WHERE Thing_Name = ?;
ENDSQL
$st{'AddThing'} = $cn->prepare(<<ENDSQL);
INSERT INTO Things
( Thing_One, Thing_Two, Thing_Name )
VALUES
( ?, ?, ? );
ENDSQL
sub closedb (
foreach my $stmt ( keys %st ) { $st{$stmt}->finish; }
$cn->disconnect;
}
# Main Code
$st{'GetThings'}->execute('Albert');
# fetch* here.
# ...
# All Done, clean up now:
&closedb;
__END__
Then you can easily copy or re-arrange SQL, and just call &closedb when you're finished with db access in the program. It's not OO, it's probably not even a polite way to use global variables (nothing is passed in to &closedb), but it's easy to read, and fast to code, and I like it.
If you want to try different SQL, just copy the statement you want to mess with, change the key on one copy to something else (eg, 'DoNotLoseOriginal'), and rock.
--
Spring: Forces, Coiled Again!
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.