Ruby Database Access - DBI Tutorial
This chapter explains how to access databases using Ruby.Ruby DBI The module provides Ruby scripts with a database-independent interface similar to Perl's DBI module.
DBI stands for Database Independent Interface, representing Ruby's database-independent interface. DBI provides an abstraction layer between Ruby code and the underlying database, allowing you to switch databases easily. It defines a set of methods, variables, and conventions, providing a consistent database-independent interface.
DBI can interact with the following:
- ADO (ActiveX Data Objects)
- DB2
- Frontbase
- mSQL
- MySQL
- ODBC
- Oracle
- OCI8 (Oracle)
- PostgreSQL
- Proxy/Server
- SQLite
- SQLRelay
DBI application architecture
DBI is independent of any database available in the background. Whether you use Oracle, MySQL, or Informix, you can use DBI. The following architecture diagram illustrates this clearly.
The general Ruby DBI architecture uses two layers:
- Database Interface (DBI) layer. This layer is database-independent and provides a set of common access methods that work regardless of the database server type.
- Database Driver (DBD) layer. This layer is database-dependent; different drivers provide access to different database engines. MySQL, PostgreSQL, InterBase, Oracle, etc. each use different drivers. Each driver is responsible for interpreting requests from the DBI layer and mapping them to requests appropriate for the given type of database server.
Installation
If you want to write a Ruby script to access a MySQL database, you first need to install the Ruby MySQL module.
Install the MySQL development package
Ubuntu
sudo
apt
get
install
mysql
client
sudo
apt
get
install
libmysqlclient15
dev
Centos
yum
install
mysql
devel
On Mac OS, you need to modify the ~/.bash_profile or ~/.profile file and add the following code:
MYSQL
=/
usr
/
local
/
mysql
/
bin
export
PATH
=
$PATH
:
$MYSQL
export
DYLD_LIBRARY_PATH
=/
usr
/
local
/
mysql
/
lib
:
$DYLD_LIBRARY_PATH
Or use a symbolic link:
sudo
ln
s
/
usr
/
local
/
mysql
/
lib
/
libmysqlclient
.18
.
dylib
/
usr
/
lib
/
libmysqlclient
.18
.
dylib
Install DBI using RubyGems (recommended)
RubyGems was created around November 2003 and became part of the Ruby standard library starting with Ruby 1.9. For more details, see:Ruby RubyGems
Install dbi and dbd-mysql using gem:
sudo
gem
install
dbi
sudo
gem
install
mysql
sudo
gem
install
dbd
mysql
Install from source (use this method for Ruby versions earlier than 1.9)
This module is a DBD that can be downloaded from http://tmtm.org/downloads/mysql/ruby/ the link above.
After downloading the latest package, extract it, enter the directory, and run the following command to install:
ruby
extconf
.
rb
or
ruby
extconf
.
rb
--
with
mysql
dir
=/
usr
/
local
/
mysql
or
ruby
extconf
.
rb
--
with
mysql
config
Then compile:
make
Get and install Ruby/DBI
You can download and install the Ruby DBI module from the following link:
https://github.com/erikh/ruby-dbi
Before starting the installation, make sure you have root privileges. Now, follow the steps below to install:
Step 1
git
clone
https
://
github
.
com
/
erikh
/
ruby
dbi
.
git
Or simply download the zip package and extract it.
Step 2
Enter the directory ruby-dbi-master, and in that directory use the setup.rb script to configure. The most common configuration command is config with no arguments. By default, this command configures all drivers to be installed.
ruby
setup
.
rb
config
More specifically, you can use the --with option to list the specific parts you want. For example, to configure only the main DBI module and the MySQL DBD layer driver, enter the following command:
ruby
setup
.
rb
config
--
with
=
dbi
,
dbd_mysql
Step 3
The final step is to build the driver; install it using the following command:
ruby
setup
.
rb
setup
ruby
setup
.
rb
install
Database connection
Assuming we're using a MySQL database, before connecting to the database, make sure:
- You have created a database named TESTDB.
- You have created the table EMPLOYEE in TESTDB.
- This table has the fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
- Set the user ID "testuser" and password "test123" to access TESTDB.
- The Ruby module DBI has been correctly installed on your machine.
- You have gone through the MySQL tutorial and understand basic MySQL operations.
The following is an example of connecting to the MySQL database "TESTDB":
Example
!/usr/bin/ruby -w
require
"
dbi
"
begin
Connect to the MySQL server
dbh
=
DBI
.
connect
(
"
DBI:Mysql:TESTDB:localhost
"
,
"
testuser
"
,
"
test123
"
)
Get the server version string and display it
row
=
dbh
.
select_one
(
"
SELECT VERSION()
"
)
puts
"
Server version:
"
row
[
0
]
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
When this script is run, the following result will be produced on a Linux machine.
Server version: 5.0.45
If the connection is established with a data source, a Database Handle is returned and saved to dbh for later use; otherwise dbh will be set to a nil value,e.err and e::errstr return the error code and error string, respectively.
Finally, before exiting the program, make sure to close the database connection and release resources.
INSERT Operation
When you want to create records in a database table, the INSERT operation is used.
Once the database connection is established, we can prepare to use the do The method or the prepare and execute method to create tables or create records to insert into a table.
Using the do statement
Statements that do not return rows can be executed by calling the do database processing method. This method takes a statement string as a parameter and returns the number of rows affected by the statement.
dbh
.
do
(
"
DROP TABLE IF EXISTS EMPLOYEE
"
)
dbh
.
do
(
"
CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )
"
)
;
Similarly, you can execute SQL INSERT statements to create records inserted into the EMPLOYEE table.
Example
!/usr/bin/ruby -w
require
"
dbi
"
begin
Connect to the MySQL server
dbh
=
DBI
.
connect
(
"
DBI:Mysql:TESTDB:localhost
"
,
"
testuser
"
,
"
test123
"
)
dbh
.
do
(
"
INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)
"
)
puts
"
Record has been created
"
dbh
.
commit
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
dbh
.
rollback
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
Use prepare and execute
You can use DBI's prepare and execute method to execute SQL statements in Ruby code.
The steps to create a record are as follows:
- Prepare the SQL statement with the INSERT statement. This will be done by using prepare methods.
- Execute the SQL query to select all results from the database. This will be done by using execute methods.
- Release the statement handle. This will be done by using finish API.
- If everything goes well, then commit the operation; otherwise you can rollback complete the transaction.
The following is the syntax for using these two methods:
Example
sth
=
dbh
.
prepare
(
statement
)
sth
.
execute
...
zero
or
more
SQL
operations
...
sth
.
finish
These two methods can be used to pass bind values to an SQL statement. Sometimes the value to be input may not be given in advance; in that case, bound values are used. Use a question mark (?) in place of the actual value, which is passed through the execute() API.
The following example creates two records in the EMPLOYEE table:
Example
!/usr/bin/ruby -w
require
"
dbi
"
begin
Connect to the MySQL server
dbh
=
DBI
.
connect
(
"
DBI:Mysql:TESTDB:localhost
"
,
"
testuser
"
,
"
test123
"
)
sth
=
dbh
.
prepare
(
"
INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (?, ?, ?, ?, ?)
"
)
sth
.
execute
(
'
John
'
,
'
Poul
'
,
25
,
'
M
'
,
2300
)
sth
.
execute
(
'
Zara
'
,
'
Ali
'
,
17
,
'
F
'
,
1000
)
sth
.
finish
dbh
.
commit
puts
"
Record has been created
"
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
dbh
.
rollback
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
If multiple INSERTs are used at the same time, it is much more efficient to prepare a statement first and then execute it multiple times in a loop than to call do each time through the loop.
READ Operation
A READ operation on any database refers to retrieving useful information from the database.
Once the database connection is established, we can prepare to query the database. We can use the do The method or the prepare and execute method to retrieve values from a database table.
The steps to retrieve records are as follows:
- Prepare the SQL query based on the required conditions. This will be done by using prepare methods.
- Execute the SQL query to select all results from the database. This will be done by using execute methods.
- retrieve the results one by one and output them. This will be done by using fetch methods.
- Release the statement handle. This will be done by using finish methods.
The following example queries all records with a salary greater than 1000 from the EMPLOYEE table.
Example
!/usr/bin/ruby -w
require
"
dbi
"
begin
Connect to the MySQL server
dbh
=
DBI
.
connect
(
"
DBI:Mysql:TESTDB:localhost
"
,
"
testuser
"
,
"
test123
"
)
sth
=
dbh
.
prepare
(
"
SELECT * FROM EMPLOYEE WHERE INCOME > ?
"
)
sth
.
execute
(
1000
)
sth
.
fetch
do
|
row
|
printf
"
First Name: %s, Last Name : %s
\n
"
,
row
[
0
]
,
row
[
1
]
printf
"
Age: %d, Sex : %s
\n
"
,
row
[
2
]
,
row
[
3
]
printf
"
Salary :%d
\n
\n
"
,
row
[
4
]
end
sth
.
finish
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
This will produce the following result:
First Name: Mac, Last Name : Mohan
Age: 20, Sex : M
Salary :2000
First Name: John, Last Name : Poul
Age: 25, Sex : M
Salary :2300
There are many other methods for retrieving records from a database. If you are interested, you can check Ruby DBI Read Operations。
Update Operation
An UPDATE operation on any database refers to updating one or more existing records in the database. The following example updates all records where SEX is 'M'. Here, we will increase the AGE of all males by one year. This is done in three steps:
- Prepare the SQL query based on the required conditions. This will be done by using prepare methods.
- Execute the SQL query to select all results from the database. This will be done by using execute methods.
- Release the statement handle. This will be done by using finish methods.
- If everything goes well, then commit the operation; otherwise you can rollback complete the transaction.
Example
!/usr/bin/ruby -w
require
"
dbi
"
begin
Connect to the MySQL server
dbh
=
DBI
.
connect
(
"
DBI:Mysql:TESTDB:localhost
"
,
"
testuser
"
,
"
test123
"
)
sth
=
dbh
.
prepare
(
"
UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = ?
"
)
sth
.
execute
(
'
M
'
)
sth
.
finish
dbh
.
commit
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
dbh
.
rollback
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
DELETE Operation
When you want to delete records from a database, the DELETE operation is used. The following example deletes all records with AGE over 20 from EMPLOYEE. The steps of this operation are as follows:
- Prepare the SQL query based on the required conditions. This will be done by using prepare methods.
- Execute the SQL query to delete the required records from the database. This will be done by using execute methods.
- Release the statement handle. This will be done by using finish methods.
- If everything goes well, then commit the operation; otherwise you can rollback complete the transaction.
Example
!/usr/bin/ruby -w
require
"
dbi
"
begin
Connect to the MySQL server
dbh
=
DBI
.
connect
(
"
DBI:Mysql:TESTDB:localhost
"
,
"
testuser
"
,
"
test123
"
)
sth
=
dbh
.
prepare
(
"
DELETE FROM EMPLOYEE WHERE AGE > ?
"
)
sth
.
execute
(
20
)
sth
.
finish
dbh
.
commit
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
dbh
.
rollback
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
Executing transactions
A transaction is a mechanism that ensures transactional consistency. A transaction should have the following four properties:
- **Atomicity:** The atomicity of a transaction means that the programs contained in a transaction, as the logical unit of work of the database, either execute all of their data-modification operations or none of them at all.
- **Consistency:** The consistency of a transaction means that the database must be in a consistent state both before and after the transaction is executed. If the state of the database satisfies all integrity constraints, the database is said to be consistent.
- **Isolation:** The isolation of a transaction means that concurrent transactions are isolated from one another; that is, the operations inside a transaction and the data being operated on must be locked and not visible to other transactions attempting to modify them.
- **Durability:** The durability of a transaction means that when a system or medium fails, the updates of committed transactions are guaranteed not to be lost. That is, once a transaction is committed, its changes to the data in the database should be permanent and able to withstand any database system failure. Durability is guaranteed through database backup and recovery.
DBI provides two methods for executing transactions. One is the commit or rollback method, used to commit or roll back a transaction. The other is the transaction method, which can be used to implement transactions. Next we will introduce these two simple methods of implementing transactions:
Method I
The first method uses DBI's commit and rollback method to explicitly commit or cancel a transaction:
Example
dbh
[
'
AutoCommit
'
]
=
false
Set auto-commit to false.
begin
dbh
.
do
(
"
UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'John'
"
)
dbh
.
do
(
"
UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'Zara'
"
)
dbh
.
commit
rescue
puts
"
transaction failed
"
dbh
.
rollback
end
dbh
[
'
AutoCommit
'
]
=
true
Method II
The second method uses the transaction method. This method is relatively simpler because it requires a code block containing the statements that make up the transaction.transaction The method executes the block and then, depending on whether the block executed successfully, automatically calls commit or rollback:
Example
dbh
[
'
AutoCommit
'
]
=
false
Set auto-commit to false
dbh
.
transaction
do
|
dbh
|
dbh
.
do
(
"
UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'John'
"
)
dbh
.
do
(
"
UPDATE EMPLOYEE SET AGE = AGE+1 WHERE FIRST_NAME = 'Zara'
"
)
end
dbh
[
'
AutoCommit
'
]
=
true
COMMIT operation
Commit is an operation that marks the database as having completed its changes; after this operation, all changes are irreversible.
The following is a simple example of calling the commit method.
dbh
.
commit
ROLLBACK operation
If you are not satisfied with one or more changes and want to completely restore them, use the rollback method.
The following is a simple example of calling the rollback method.
dbh
.
rollback
Disconnecting from the Database
To disconnect from the database, use the disconnect API.
dbh
.
disconnect
If a user closes the database connection through the disconnect method, DBI will roll back all unfinished transactions. However, without relying on any DBI implementation details, your application can explicitly call commit or rollback.
Handling errors
There are many different sources of errors, such as syntax errors when executing SQL statements, connection failures, or calling the fetch method on a statement handle that has already been cancelled or finished.
If a DBI method fails, DBI throws an exception. DBI methods can throw any type of exception, but the two most important exception classes are DBI::InterfaceError and DBI::DatabaseError。
Exception objects of these classes have err、errstr and state three attributes, representing respectively the error number, a descriptive error string, and a standard error code. The attributes are described in detail below:
- **err:** Returns the integer representation of the error that occurred, or if not supported by the DBD, returns nil. For example, the Oracle DBD returns ORA-XXXX the numeric part of the error message.
- **errstr:** Returns the string representation of the error that occurred.
- **state:** Returns the SQLSTATE code of the error that occurred. SQLSTATE is a five-character string. Most DBDs do not support it, so nil is returned.
In the example above you have seen the following code:
rescue
DBI
::
DatabaseError
=>
e
puts
"
An error occurred
"
puts
"
Error code: #{e.err}
"
puts
"
Error message: #{e.errstr}
"
dbh
.
rollback
ensure
Disconnect from the server
dbh
.
disconnect
if
dbh
end
To obtain debugging information about what the script is doing when it runs, you can enable tracing. To do this, you must first download the dbi/trace module, and then call the method that controls the tracing mode and output destination. trace method in the component:
require
"
dbi/trace
"
..............
trace
(
mode
,
destination
)
The value of mode can be 0 (off), 1, 2 or 3, and the value of destination should be an IO object. The default values are 2 and STDERR, respectively.
Code Blocks for Methods
There are some methods for creating handles. These methods are called with code blocks. The advantage of using a code block with a method is that they provide the handle as a parameter to the block, and the handle is automatically cleaned up when the block terminates. Here are some examples to help understand this concept.
- **DBI.connect:** This method generates a database handle; it is recommended to call the disconnect at the end of the block to disconnect from the database.
- **dbh.prepare:** This method generates a statement handle; it is recommended to call the finishat the end of the block. Inside the block, you must call the execute method to execute the statement.
- **dbh.execute:** This method is similar to dbh.prepare, but dbh.execute does not need to call the execute method inside the block. The statement handle is executed automatically.
Example 1
DBI.connect It can take a code block, to which the database handle is passed, and the handle is automatically disconnected at the end of the block.
dbh = DBI.connect("DBI:Mysql:TESTDB:localhost",
"testuser", "test123") do |dbh|
Example 2
dbh.prepare It can take a code block, to which the statement handle is passed, and finish is automatically called at the end of the block.
dbh
.
prepare
(
"
SHOW DATABASES
"
)
do
|
sth
|
sth
.
execute
puts
"
Databases:
"
sth
.
fetch_all
.
join
(
"
,
"
)
end
Example 3
dbh.execute It can take a code block, to which the statement handle is passed, and finish is automatically called at the end of the block.
dbh
.
execute
(
"
SHOW DATABASES
"
)
do
|
sth
|
puts
"
Databases:
"
sth
.
fetch_all
.
join
(
"
,
"
)
end
DBI transaction The method can also take a code block, which was explained in the previous section.
Driver-Specific Functions and Attributes
DBI allows database drivers to provide additional database-specific functions, which can be called by users through the func method of any Handle object.
Use []= or [] The method can set or get driver-specific attributes.
DBD::Mysql implements the following driver-specific functions:
| No. | Function & Description |
|---|---|
| 1 | dbh.func(:createdb, db_name) |
| Create a new database. | |
| 2 | dbh.func(:dropdb, db_name) |
| Delete a database. | |
| 3 | dbh.func(:reload) |
| Perform a reload operation. | |
| 4 | dbh.func(:shutdown) |
| Shut down the server. | |
| 5 | dbh.func(:insert_id) => Fixnum |
| Return the most recent AUTO_INCREMENT value for the connection. | |
| 6 | dbh.func(:client_info) => String |
| Return MySQL client information according to the version. | |
| 7 | **dbh.func(:client_version) => Fixnum ** |
| Return client information according to the version. This is similar to :client_info, but it returns a fixnum instead of a string. | |
| 8 | dbh.func(:host_info) => String |
| Return host information. | |
| 9 | dbh.func(:proto_info) => Fixnum |
| Return the protocol used for communication. | |
| 10 | **dbh.func(:server_info) => String ** |
| Return MySQL server information according to the version. | |
| 11 | **dbh.func(:stat) => Stringb> |
| Return the current status of the database.** | |
| 12 | dbh.func(:thread_id) => Fixnum |
| Return the ID of the current thread. |
#!/usr/bin/ruby require "dbi" begin # Connect to the MySQL server dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") puts dbh.func(:client_info) puts dbh.func(:client_version) puts dbh.func(:host_info) puts dbh.func(:proto_info) puts dbh.func(:server_info) puts dbh.func(:thread_id) puts dbh.func(:stat) rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" ensure dbh.disconnect if dbh end
This will produce the following result:
5.0.45
50045
Localhost via UNIX socket
10
5.0.45
150621
Uptime: 384981 Threads: 1 Questions: 1101078 Slow queries: 4 \
Opens: 324 Flush tables: 1 Open tables: 64 \
Queries per second avg: 2.860