Database Reference
In-Depth Information
my $dsn = "DBI:mysql:host=localhost;database=cookbook"
. ";mysql_socket=/var/tmp/mysql.sock" ;
To specify the port number for non- localhost (TCP/IP) connections, provide a port
option:
my $dsn = "DBI:mysql:host=127.0.0.1;database=cookbook;port=3307" ;
Ruby
To write MySQL scripts in Ruby, the DBI module must be installed, as well as the
MySQL-specific driver module. To obtain these modules if they're not already installed,
see the Preface .
The following Ruby script, connect.rb , connects to the MySQL server, selects cook
book as the default database, and disconnects:
#!/usr/bin/ruby -w
# connect.rb: connect to the MySQL server
require "dbi"
begin
dsn = "DBI:Mysql:host=localhost;database=cookbook"
dbh = DBI . connect ( dsn , "cbuser" , "cbpass" )
puts "Connected"
rescue
puts "Cannot connect to server"
exit ( 1 )
end
dbh . disconnect
puts "Disconnected"
To try connect.rb , 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:
% ruby connect.rb
Connected
Disconnected
For background on running Ruby programs, read “Executing Programs from the Com‐
mand Line” on the companion website (see the Preface ).
The -w option turns on warning mode so that Ruby produces warnings for any ques‐
tionable constructs. Our example script has no such constructs, but it's a good idea to
get in the habit of using -w to catch problems that occur during the script development
process.
Search WWH ::




Custom Search