Database Reference
In-Depth Information
Connecting to MySQL
To query adatabase with Ruby, we will need to establish a connection with MySQL.
Here's the beginning part of a Ruby program to do this:
require 'mysql'
user = 'admin_backup'
password = 'its_password_123'
host = 'localhost'
database = 'server_admin'
begin
con = Mysql . new host , user , password , database
# Database Queries Here
# ...
rescue Mysql : :Error => e
puts e . errno
puts e . error
ensure
con . close if con
end
This excerpt of a Ruby program shows how to connect and disconnect from MySQL. The
first line is the usual line to invoke Ruby. The next line calls the MySQL module. Then
there is a list of variables that we'll use for connecting to the server. The names of these
variables are not important.
This is followed by a begin statement that will include all of the interactions with the
database server. The first line establishes a new connection to MySQL. It includes the
variables we created for connecting to the server. These variables, or values for these
parameters, must be in the order shown here.
Once you have successfully connected to the database server, you can execute SQL state-
ments. I left out the lines for querying the database to keep this part simple. We'll look at
that in a bit.
If the program is not successful in connecting to MySQL, the rescue block will handle
the errors and display them to the user using puts . Regardless of whether the processing
of the queries is successful, the ensure will make sure that the connection to MySQL is
closed at the end of the program.
Search WWH ::




Custom Search