Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Mixing Mysql and Perl

by paulbort (Hermit)
on Jan 12, 2004 at 19:53 UTC ( [id://320752]=note: print w/replies, xml ) Need Help??


in reply to Mixing Mysql and Perl

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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://320752]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2024-04-19 04:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found