Database Reference
In-Depth Information
DBI:mysql:host
=
localhost
;
database
=
cookbook
DBI:mysql:database
=
cookbook
To select no default database, omit the
database
option.
The second and third arguments of the
connect()
call are your MySQL username and
password. Following the password, you can also provide a fourth argument to specify
attributes that control DBI's behavior when errors occur. With no attributes, DBI by
default prints error messages when errors occur but does not terminate your script.
That's why
connect.pl
checks whether
connect()
returns
undef
, which indicates failure:
my
$dbh
=
DBI
->
connect
(
$dsn
,
"cbuser"
,
"cbpass"
)
or
die
"Cannot connect to server\n"
;
Other error-handling strategies are possible. For example, to tell DBI to terminate the
script if an error occurs in any DBI call, disable the
PrintError
attribute and enable
RaiseError
instead:
my
$dbh
=
DBI
->
connect
(
$dsn
,
"cbuser"
,
"cbpass"
,
{
PrintError
=>
0
,
RaiseError
=>
1
});
Then you need not check for errors yourself. The trade-off is that you also lose the ability
to decide how your program recovers from errors.
Recipe 2.2
discusses error handling
further.
Another common attribute is
AutoCommit
, which sets the connection's auto-commit
mode for transactions. MySQL enables this by default for new connections, but we'll
set it from this point on to make the initial connection state explicit:
my
$dbh
=
DBI
->
connect
(
$dsn
,
"cbuser"
,
"cbpass"
,
{
PrintError
=>
0
,
RaiseError
=>
1
,
AutoCommit
=>
1
});
As shown, the fourth argument to
connect()
is a reference to a hash of attribute name/
value pairs. An alternative way of writing this code follows:
my
$conn_attrs
=
{
PrintError
=>
0
,
RaiseError
=>
1
,
AutoCommit
=>
1
};
my
$dbh
=
DBI
->
connect
(
$dsn
,
"cbuser"
,
"cbpass"
,
$conn_attrs
);
Use whichever style you prefer. Scripts in this topic use the
$conn_attr
hashref to make
connect()
calls simpler to read.
Assuming that
connect()
succeeds, it returns a database handle that contains infor‐
mation about the state of the connection. (In DBI parlance, references to objects are
called handles.) Later we'll see other handles such as statement handles, which are as‐
sociated with particular statements. Perl DBI scripts in this topic conventionally use
$dbh
and
$sth
to signify database and statement handles.
Additional connection parameters.
To specify the path to a socket file for
localhost
con‐
nections on Unix, provide a
mysql_socket
option in the DSN: