$dbh = DBI->connect($data_source, $username, $password)
          || die $DBI::errstr;
$dbh = DBI->connect($data_source, $username, $password, \%attr)
          || die $DBI::errstr;

connect establishes a database connection, or session, to the requested $data_source . Returns a database handle object if the connection succeeds. Use $dbh->disconnect to terminate the connection.

If the connect fails (see below), it returns undef and sets both $DBI::err and $DBI::errstr. (It does not set $!, etc.) You should generally test the return status of connect and print $DBI::errstr if it has failed.

Multiple simultaneous connections to multiple databases through multiple drivers can be made via the DBI. Simply make one connect call for each database and keep a copy of each returned database handle.

The $data_source value should begin with dbi: driver_name :. The driver_name specifies the driver that will be used to make the connection. (Letter case is significant.)

As a convenience, if the $data_source parameter is undefined or empty, the DBI will substitute the value of the environment variable DBI_DSN. If just the driver_name part is empty (i.e., the $data_source prefix is dbi::), the environment variable DBI_DRIVER is used. If neither variable is set, then connect dies.

Examples of $data_source values are:


There is no standard for the text following the driver ...

Get Programming the Perl DBI now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.