in reply to Re: dbh->disconnect or leave to scope
in thread dbh->disconnect or leave to scope

We probably have 200 methods that connect to the db to do something, it's a pain having to $sth->finish and $dbh->disconnect at the end of every one, if they're both going to be called anyway when I return from the sub.

  • Comment on Re^2: dbh->disconnect or leave to scope

Replies are listed 'Best First'.
Re^3: dbh->disconnect or leave to scope
by Tux (Canon) on Jan 19, 2011 at 07:57 UTC

    Only if $dbh is scoped to the sub. If $dbh is scoped to the file or the module, it is not disconnecting at the return from the sub.

    Personally I never disconnect, which has several reasons:

    • Most of my script/programs use the database from start to finish, so there is no use in disconnecting half-way through.
    • Connects to remote databases is very costly, so I rather have the database handle survive as long as possible.
    • Cleaning up my handles, certainly for prepared statements and cursors, should already give the server enough room to clean up for my session. Only having the session/handle open won't hurt the server too much. Note that I am using the handle, not just keeping it open to pester the server.
    • I am also working with a database that has a very nasty bug in opening a new handle to the same database (for some versions of this database server). It will simply die (in very different variations of die ranging from a database crash to a script exit). As I mostly script for database-agnostic processes, I rather prevent this from happening.

    Personally, I think scoped cleanup is the neatest way to manage database resources, but YMMV. The local DBA certainly should have a word in the matter.

    FWIW I manage two DBD's on CPAN and am co-maint of DBI.


    Enjoy, Have FUN! H.Merijn
Re^3: dbh->disconnect or leave to scope
by mje (Curate) on Jan 19, 2011 at 09:15 UTC

    Why would you call finish? From the DBI docs - Indicate that no more data will be fetched from this statement handle before it is either executed again or destroyed. You almost certainly do not need to call this method. I thought the only useful case for finish is when you absolutely know there are more rows you have not read and you know you are not going to read them. If I had not read all rows but intended to that would be a bug in my code and calling finish might mask that.

    As for not disconnecting and letting scope handle it I'd just warn you that this can be a pain to debug if your code is wrong e.g., if you fail to commit a transaction in part A of your code and the connection handle goes out of scope in part B of your code and DBI rolls it back. You'll get a warning of the rollback when the handle goes out of scope at B but the problem code is at A.