Database Reference
In-Depth Information
nection. It's also preferable to close the connection explicitly. If a program simply
terminates, the MySQL server eventually notices, but an explicit close on the user
end enables the server to perform an immediate orderly close on its end.
This section includes example programs that show how to use each API to connect to
the server, select the
cookbook
database, and disconnect. The discussion for each API
also indicates how to connect without selecting any default database. This might be the
case if you plan to execute a statement that doesn't require a default database, such as
SHOW
VARIABLES
or
SELECT
VERSION()
. Or perhaps you're writing a program that enables
the user to specify the database after the connection has been made.
The scripts shown here use
localhost
as the hostname. If they pro‐
duce a connection error indicating that a socket file cannot be found,
try changing
localhost
to
127.0.0.1
, the TCP/IP address of the local
host. This tip applies throughout the topic.
Perl
To write MySQL scripts in Perl, the DBI module must be installed, as well as the MySQL-
specific driver module, DBD::mysql. To obtain these modules if they're not already
installed, see the
Preface
.
The following Perl script,
connect.pl
, connects to the MySQL server, selects
cookbook
as the default database, and disconnects:
#!/usr/bin/perl
# connect.pl: connect to the MySQL server
use
strict
;
use
warnings
;
use
DBI
;
my
$dsn
=
"DBI:mysql:host=localhost;database=cookbook"
;
my
$dbh
=
DBI
->
connect
(
$dsn
,
"cbuser"
,
"cbpass"
)
or
die
"Cannot connect to server\n"
;
print
"Connected\n"
;
$dbh
->
disconnect
();
print
"Disconnected\n"
;
To try
connect.pl
, locate it under the
api
directory of the
recipes
distribution and run
it from the command line. The program should print two lines indicating that it con‐
nected and disconnected successfully:
%
perl connect.pl
Connected
Disconnected