in reply to Re: Database Connections
in thread Database Connections

My question about the above approach is that I would still be creating a db connection everytime I need to use the db, right? In other words, if for one script instantiation I call two sub routines, test1 and test2 and they both use the db then they both will be creating two separate db connections, right?
test1(); test2(); sub test1 { $dbh=new MyDBLayer; $dbh->do(etc..); } sub test2 { $dbh=new MyDBLayer; $dbh->do(etc..); }
It is best to minimize the number of times you have to make a db connection right? If I do it this way though, I only make one db connection but use it in two subroutines.
$dbh=new db connection; test1($dbh); test2($dbh); sub test1 { $dbh->do(etc..); } sub test2 { $dbh->do(etc..); }
Is it wrong to do it this way?
Thanks.

Replies are listed 'Best First'.
Re: Re: Re: Database Connections
by Fastolfe (Vicar) on Jan 15, 2001 at 20:19 UTC
    No, they'll be returning the same $dbh. The use of the ||= operator is equivalent to $dbh = $dbh || DBI->connect(...);. Thus, $dbh will be connected the first time (since it hasn't been defined yet), but will simply be re-used each additional time the function is called.
Re: Re: Re: Database Connections
by chipmunk (Parson) on Jan 15, 2001 at 20:23 UTC
    Actually, Fastolfe's suggestion allows you to only create a single DB connection for the life of the script.

    The first time new MyDBLayer is called, the variable $dbh will be undef, so a database connection will be created. The second time new MyDBLayer is called, $dbh will already hold a database object; that object will be returned, instead of a new connection being made.

    The key is the use of the ||= operator; a new database connection will be made only if $dbh doesn't already hold a database object.

    Personally, I've used the approach of passing a database connection into a subroutine, but I really like Fastolfe's approach.