[San-Diego-pm] Scope

Emile Aben emileaben at yahoo.com
Mon Aug 2 11:04:29 CDT 2004


Hi Joel,

Some cookbook/common-practice examples in
DBI-programming can be found here:
http://perlmonks.org/index.pl?node_id=284436

In my opinion it's better to write a separate piece of
code to provide common database-functions, and maybe
put it in a package.
For instance: for DBI connections you could write a
function that returns the databasehandle:

package MyDB;
use DBI;
sub connect {
   my $dbh;
              
$dbh=DBI->connect("DBI:mysql:ShopCart","root",undef,{PrintError=>1,RaiseError=>1});

   #insert errorhandling code here

   return $dbh;
}

you could use this in all modules like this:
   use MyDB;
   my $dbh=MyDB::connect();

Big advantage here is that you don't have to change
all your scripts if you decide to use another
database/user/password, or want specific attributes
set on all DBI-handles that your application uses.

Emile

--- Joel Fentin <joel at fentin.com> wrote:

> I am working on an application which has different
> programs (main 
> modules) that all share the same database.
> ModifyProduct.pl, 
> AddProduct.pl, and DeleteProduct.pl for example. And
> there are more. 
> Only one runs at a time.
> 
> I can repeat lines like the following and many
> others in each program:
> 
> my $dbh;
> $dbh = 
>
DBI->connect("DBI:mysql:ShopCart","root",undef,{PrintError=>1,RaiseError=>1});
> my $ref = $dbh->selectall_arrayref("$Select $From
> $Where $Order");
> 
> Or I can set up a package for all of that
> (Utility.pl) where I stick all 
> such utilities. And if I do so, and if I open the
> database connection in 
> the utility, I presume I must do ALL database work
> through the utility.
> 
> At the moment it feels handier to simply duplicate
> the above lines and 
> many others in each main module.
> 
> I have no size or speed issues.
> 
> =====================
> 
> Currently I leave the connection to the database
> open until the program 
> no longer runs. Perhaps I should open, do a select,
> and close with each 
> call to the database?
> 
> =====================
> 
> Are there common practices I should be aware of? Any
> suggestions?
> 
> -- 
> Joel Fentin    tel: 760-749-8863    FAX:
> 760-749-8864
> Contact me:    http://fentin.com/me/ContactMe.html
> Biz:           http://fentin.com
> Personal:      http://fentin.com/me/
> _______________________________________________
> San-Diego-pm mailing list
> San-Diego-pm at pm.org
> http://www.pm.org/mailman/listinfo/san-diego-pm
> 


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 



More information about the San-Diego-pm mailing list