Connecting to and disconnecting from a database
Connecting and disconnecting is simple: just use connect
and disconnect
methods.
In case of SQLite
where a database is a file,
we do not have to provide a username
and password
.
my $dbh = DBI->connect('dbi:SQLite:database.db') or die "Can't connect to database: " . DBI->errstr; # do some queries here $dbh->disconnect;
The first connect
parameter is called a data_source
where you should provide a database driver name (SQLite
in our case) and its parameters (path to database in our case).
When database is not available connect
methods fails to return a $dbh
object and usually it is a good practice to stop right there dying with an error that is located in DBI->errstr
.
Calling disconnect
usually is not required. Automatic disconnect is performed as soon as $dbh
variable is out of scope.
If you don't want to check every call for a return value, you can set a RaiseError
attribute and exceptions will be raise automatically.
my $dbh = DBI->connect('dbi:SQLite:database.db', undef, undef, {RaiseError => 1}); # do some queries here $dbh->disconnect;