Database Reference
In-Depth Information
If you don't catch connection errors explicitly with eval , you can write the script body
more simply:
my $dbh = Cookbook:: connect ();
print "Connected\n" ;
$dbh -> disconnect ();
print "Disconnected\n" ;
In this case, Perl catches any connection exception and terminates the script after print‐
ing the error message generated by the connect() method.
Ruby
The following Ruby library file, Cookbook.rb , defines a Cookbook class that implements
a connect class method:
# Cookbook.rb: library file with utility method for connecting to MySQL
# using the Ruby DBI module
require "dbi"
# Establish a connection to the cookbook database, returning a database
# handle. Raise an exception if the connection cannot be established.
class Cookbook
@@host_name = "localhost"
@@db_name = "cookbook"
@@user_name = "cbuser"
@@password = "cbpass"
# Class method for connecting to server to access the
# cookbook database; returns a database handle object.
def Cookbook . connect
return DBI . connect ( "DBI:Mysql:host= #{ @@host_name } ;database= #{ @@db_name } " ,
@@user_name , @@password )
end
end
The connect method is defined in the library as Cookbook.connect because Ruby class
methods are defined as class_name.method_name .
Ruby locates library files by searching the list of directories named in its $LOAD_PATH
variable (also known as $: ), which is an array. To check the default value of this variable
on your system, use interactive Ruby to execute this statement:
% irb
>> puts $LOAD_PATH
If you install a library file in one of those directories, your scripts will find it automat‐
ically. If you install the file somewhere else, tell your scripts where to find it by setting
the RUBYLIB environment variable, as discussed in the introductory part of this recipe.
Search WWH ::




Custom Search