DBI: disconnect - question
Asked Answered
B

4

7

Would you call parts of the disconnect-code as line-noise or would you leave it as it is?

use DBI;

my $dbh = DBI->connect ...
...
...
END {
    $dbh->disconnect or die $DBI::errstr if $dbh;
}
Bremerhaven answered 16/3, 2011 at 12:9 Comment(1)
At the very least, using RaiseError or HandleError, you don't need the 'or die ...'Yabber
M
3

Explicit disconnection from the database is not strictly necessary if you are exiting from your program after you have performed all the work. But it is a good idea, especially in programs in which you have performed multiple connections or will be carrying out multiple sequential connections.

See Programming the Perl DBI for more info.

Mcgowen answered 16/3, 2011 at 12:27 Comment(1)
The link has died. Here's a link to what it looked like when it last had content. web.archive.org/web/20141018180208/http://oreilly.com/catalog/…Donatello
P
2

Be careful. You can hit some interesting situations if you disable AutoCommit and don't commit depending on whether you disconnect:

perl -le 'use DBI;my $h = DBI->connect("dbi:ODBC:test","test","test", {AutoCommit => 0, RaiseError=>1}); $h->do(q/insert into mje values(?, ?)/, undef, 1, "fred");'

Issuing rollback() due to DESTROY without explicit disconnect() of DBD::ODBC::db handle test.

Note, because there was no explicit disconnect the insert was rolled back and we got an error.

perl -le 'use DBI;my $h = DBI->connect("dbi:ODBC:test","test","test", {AutoCommit => 0, RaiseError=>1}); $h->do(q/insert into mje values(?, ?)/, undef, 1, "fred");$h->disconnect or die $DBI::errstr;'

Here it appears there is nothing wrong even though commit was not called but the rows did not get into the database. So the disconnect masked the fact the rows were not committed.

Phalangeal answered 16/3, 2011 at 13:25 Comment(0)
E
0

At the end of the script, it probably doesn't matter much. However it might be worth it to add it anyway just to explicitly clean up after yourself. It certainly won't hurt and I suspect there might be a few situations where it will definitely help.

Entrance answered 16/3, 2011 at 12:30 Comment(0)
E
0

I don't think it is strictly necessary but I find it neater.

Endanger answered 16/3, 2011 at 15:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.