Siblings, I crave wisdom.
I have a big script which does lots of things with a db. So at the start of the script I do
$dbh = DBI->connect("DBI:mysql:database=db_name", "user_name", "password");
and then I call lots of methods on
$dbh and at the end I do
$dbh->disconnect;.
So far so no surprises.
But now I have some things I do over and over again, and not just in this but in similar scripts. So I put them in subroutines and placed them in a module. And of course these subroutines all need a database handle. And I think that I have to open (or declare or whatever) that handle in the module itself in order to get it into the right scope. So now the only options I can see are
(1)open two db handles, one in the script, for use by code that isn't being re-used, and one in the module;
(2)open one db handle in the module and use that in the script
Both of these seem a bit fraught with scoping issues that I don't understand well enough to monkey with, and (1) seems downright wasteful. In fact I'm on the point of falling back on
(3) put the subroutines back in the script
But before I despair, I wondered if some wise monk could suggest a more elegant solution. Just to sum up, I have constructed some example code. What I have at the moment is a script a bit like this:
#!/usr/bin/perl -w
use strict;
use DBI;
use dbmodule;
END {DBModule_Close}
## do various things with the db specific to this
## script, such as:
my $sth = $dbh->prepare("SELECT Foo FROM bar WHERE Foo = 'baz'");
$sth->execute;
## do various other things, which get done in lots of
## other places too, using subroutines in dbmodule:
Write_Bar;
... and then I have a module a bit like this:
package dbmodule;
require Exporter;
our @ISA = ("Exporter");
$dbh = DBI->connect("DBI:mysql:database=thinweb", "thinweb", "126368")
+;
sub
Write_Bar
{
$dbh->do("INSERT INTO bar (Foo,Fob,Fib) VALUES ('baz','biz','boz')");
}
sub
DBModule_Close
{
$dbh->disconnect;
}
our @EXPORT = qw/Write_Bar Insert_Into_BookingManager DBModule_Close/;
1;
§
George Sherston