Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DBI: disconnect - question

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;
}
like image 333
sid_com Avatar asked Mar 16 '11 12:03

sid_com


People also ask

How do I disconnect a database in Perl?

$rc = $dbh->disconnect || warn $dbh->errstr; Disconnects the database from the database handle. disconnect is typically used only before exiting the program. The handle is of little use after disconnecting.

What does a DBI do?

Data-Based Individualization (DBI) is a systematic method for using data to determine when and how to provide more intensive intervention.


2 Answers

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.

like image 127
Eugene Yarmash Avatar answered Sep 29 '22 14:09

Eugene Yarmash


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.

like image 26
bohica Avatar answered Sep 29 '22 15:09

bohica