Database Reference
In-Depth Information
The
require
statement tells Ruby to load the DBI module. It's unnecessary to load the
MySQL driver module explicitly. DBI does that itself when the script connects to the
database server.
To establish the connection, pass a data source name (DSN) and the MySQL username
and password to the
connect()
method. 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 typically has one of these formats:
DBI
:
Mysql
:
db_name
:
host_name
DBI
:
Mysql
:
name
=
value
;
name
=
value
.
.
.
As with Perl DBI, the second colon in the DSN is required even if you specify no fol‐
lowing options.
Use the DSN components as follows:
• The first component is always
DBI
or
dbi
.
• The second component tells DBI which database driver to use. For MySQL, the
name is
Mysql
.
• The third component, if present, is either a database name and hostname separated
by a colon, or 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 equiv‐
alent:
DBI
:
Mysql
:
host
=
localhost
;
database
=
cookbook
DBI
:
Mysql
:
database
=
cookbook
To select no default database, omit the
database
option.
Assuming that
connect()
succeeds, it returns a database handle that contains infor‐
mation about the state of the connection. Ruby DBI scripts in this topic conventionally
use
dbh
to signify a database handle.
If the
connect()
method fails, DBI raises an exception. To handle exceptions, put the
statements that might fail inside a
begin
block, and use a
rescue
clause that contains
the error-handling code. Exceptions that occur at the top level of a script (that is, outside