Database Reference
In-Depth Information
For background on running Perl programs, read “Executing Programs from the Com‐
mand Line” on the companion website (see the
Preface
).
The
use
strict
line turns on strict variable checking and causes Perl to complain about
any variables that are used without having been declared first. This precaution helps
find errors that might otherwise go undetected.
The
use
warnings
line turns on warning mode so that Perl produces warnings for any
questionable constructs. Our example script has none, but it's a good idea to get in the
habit of enabling warnings to catch problems that occur during the script development
process.
use
warnings
is similar to specifying the Perl
-w
command-line option, but
provides more control over which warnings to display. (For more information, execute
a
perldoc
warnings
command.)
The
use
DBI
statement tells Perl to load the DBI module. It's unnecessary to load the
MySQL driver module (DBD::mysql) explicitly. DBI does that itself when the script
connects to the database server.
The next two lines establish the connection to MySQL by setting up a data source name
(DSN) and calling the DBI
connect()
method. The arguments to
connect()
are the
DSN, the MySQL username and password, and any connection attributes you want to
specify. The DSN is required. The other arguments are optional, although usually it's
necessary to supply a username and password.
The DSN specifies which database driver to use and other options that indicate where
to connect. For MySQL programs, the DSN has the format
DBI:mysql:
options
. The
second colon in the DSN is required even if you specify no following options.
Use the DSN components as follows:
• The first component is always
DBI
. It's not case sensitive.
• The second component tells DBI which database driver to use, and it
is
case sensi‐
tive. For MySQL, the name must be
mysql
.
• The third component, if present, is a semicolon-separated list of
name
=
value
pairs
that specify additional connection options, in any order. For our purposes, the two
most relevant options are
host
and
database
, to specify the hostname where the
MySQL server is running and the default database.
Based on that information, the DSN for connecting to the
cookbook
database on the
local host
localhost
looks like this:
DBI:mysql:host
=
localhost
;
database
=
cookbook
If you omit the
host
option, its default value is
localhost
. These two DSNs are
equivalent: