Ruby 简明教程

Ruby/DBI - Database Access

本章教你如何使用 Ruby 访问数据库。Ruby DBI 模块为 Ruby 脚本提供了一个与 Perl DBI 模块类似的数据库独立接口。

This chapter teaches you how to access a database using Ruby. The Ruby DBI module provides a database-independent interface for Ruby scripts similar to that of the Perl DBI module.

DBI 代表 Ruby 的数据库独立接口,这意味着 DBI 在 Ruby 代码和底层数据库之间提供了一个抽象层,让你可以非常轻松地切换数据库实现。它定义了一组方法、变量和约定,它们提供了一个一致的数据库接口,与实际使用的数据库无关。

DBI stands for Database Independent Interface for Ruby, which means DBI provides an abstraction layer between the Ruby code and the underlying database, allowing you to switch database implementations really easily. It defines a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.

DBI 可以与以下内容交互 −

DBI can interface with the following −

  1. ADO (ActiveX Data Objects)

  2. DB2

  3. Frontbase

  4. mSQL

  5. MySQL

  6. ODBC

  7. Oracle

  8. OCI8 (Oracle)

  9. PostgreSQL

  10. Proxy/Server

  11. SQLite

  12. SQLRelay

Architecture of a DBI Application

DBI 独立于后端可用的任何数据库。无论你使用的是 Oracle、MySQL 还是 Informix 等,都可以使用 DBI。这从以下架构图中可以看出。

DBI is independent of any database available in the backend. You can use DBI whether you are working with Oracle, MySQL or Informix, etc. This is clear from the following architecture diagram.

ruby dbi

Ruby DBI 的一般架构使用两层 −

The general architecture for Ruby DBI uses two layers −

  1. The database interface (DBI) layer. This layer is database independent and provides a set of common access methods that are used the same way regardless of the type of database server with which you’re communicating.

  2. The database driver (DBD) layer. This layer is database dependent; different drivers provide access to different database engines. There is one driver for MySQL, another for PostgreSQL, another for InterBase, another for Oracle, and so forth. Each driver interprets requests from the DBI layer and maps them onto requests appropriate for a given type of database server.

Prerequisites

如果你想要编写 Ruby 脚本来访问 MySQL 数据库,则需要安装 Ruby MySQL 模块。

If you want to write Ruby scripts to access MySQL databases, you’ll need to have the Ruby MySQL module installed.

如上所述,该模块充当 DBD,并且可以从 https://www.tmtm.org/en/mysql/ruby/ 下载

This module acts as a DBD as explained above and can be downloaded from https://www.tmtm.org/en/mysql/ruby/

Obtaining and Installing Ruby/DBI

您可以使用 Ruby Gems 软件包管理器安装 Ruby DBI:

You can install ruby DBI using the Ruby Gems packaging manager:

gem install dbi

在开始此安装之前,请确保您拥有 root 权限。现在,按照以下步骤操作:

Before starting this installation make sure you have the root privilege. Now, follow the steps given below −

Step 1

$ tar zxf dbi-0.2.0.tar.gz

Step 2

进入发行版目录 dbi-0.2.0 nd,并使用该目录中的 setup.rb 脚本对其进行配置。最通用的配置命令如下所示,config 参数后不跟任何参数。此命令将发行版配置为默认安装所有驱动程序。

Go in distribution directory dbi-0.2.0 nd configure it using the setup.rb script in that directory. The most general configuration command looks like this, with no arguments following the config argument. This command configures the distribution to install all drivers by default.

$ ruby setup.rb config

要更具体,请提供一个 --with 选项,列出您想要使用的发行版的特定部分。例如,要仅配置主 DBI 模块和 MySQL DBD 级别驱动程序,请发出以下命令:

To be more specific, provide a --with option that lists the particular parts of the distribution you want to use. For example, to configure only the main DBI module and the MySQL DBD-level driver, issue the following command −

$ ruby setup.rb config --with = dbi,dbd_mysql

Step 3

最后一步是使用以下命令构建驱动程序并将其安装:

Final step is to build the driver and install it using the following commands −

$ ruby setup.rb setup
$ ruby setup.rb install

Database Connection

假设我们要使用 MySQL 数据库,在连接到数据库之前确保以下内容:

Assuming we are going to work with MySQL database, before connecting to a database make sure of the following −

  1. You have created a database TESTDB.

  2. You have created EMPLOYEE in TESTDB.

  3. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX, and INCOME.

  4. User ID "testuser" and password "test123" are set to access TESTDB.

  5. Ruby Module DBI is installed properly on your machine.

  6. You have gone through MySQL tutorial to understand MySQL Basics.

以下是连接到 MySQL 数据库“TESTDB”的示例

Following is the example of connecting with MySQL database "TESTDB"

#!/usr/bin/ruby -w

require "dbi"

begin
   # connect to the MySQL server
   dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123")
   # get 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 server
   dbh.disconnect if dbh
end

在运行此脚本时,它会在我们的 Linux 计算机上产生以下结果。

While running this script, it produces the following result at our Linux machine.

Server version: 5.0.45

如果已与数据源建立连接,则返回数据库句柄并将其保存在 dbh 中以供进一步使用,否则 dbh 将设置为 nil 值,而 e.err 和 e::errstr 将分别返回错误代码和错误字符串。

If a connection is established with the data source, then a Database Handle is returned and saved into dbh for further use otherwise dbh is set to nil value and e.err and e::errstr return error code and an error string respectively.

最后,在退出之前,请确保已关闭数据库连接且已释放资源。

Finally, before coming out it, ensure that database connection is closed and resources are released.

INSERT Operation

当您想要将记录创建到数据库表中时,需要 INSERT 操作。

INSERT operation is required when you want to create your records into a database table.

一旦建立了数据库连接,我们就可以使用 do 方法或 prepareexecute 方法在数据库表中创建表或记录。

Once a database connection is established, we are ready to create tables or records into the database tables using do method or prepare and execute method.

Using do Statement

可以通过调用 do 数据库句柄方法发出不返回行的语句。此方法采用语句字符串参数,并返回受语句影响的行数。

Statements that do not return rows can be issued by invoking the do database handle method. This method takes a statement string argument and returns a count of 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 )" );

同样,您可以执行 SQL INSERT 语句,以在 EMPLOYEE 表中创建记录。

Similarly, you can execute the SQL INSERT statement to create a record into the EMPLOYEE table.

#!/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 server
   dbh.disconnect if dbh
end

Using prepare and execute

您可以使用 DBI 类的 prepare 和 execute 方法通过 Ruby 代码执行 SQL 语句。

You can use prepare and execute methods of DBI class to execute the SQL statement through Ruby code.

记录创建采用以下步骤:

Record creation takes the following steps −

  1. Preparing SQL statement with INSERT statement. This will be done using the prepare method.

  2. Executing SQL query to select all the results from the database. This will be done using the execute method.

  3. Releasing Statement handle. This will be done using finish API

  4. If everything goes fine, then commit this operation otherwise you can rollback the complete transaction.

下面是使用这两种方法的语法 −

Following is the syntax to use these two methods −

sth = dbh.prepare(statement)
sth.execute
   ... zero or more SQL operations ...
sth.finish

这两种方法可用于将 bind 值传递给 SQL 语句。可能出现以下情况:要输入的值未提前给出。在这种情况下,将使用绑定值。问号 ( ? ) 用于替换实际值,然后通过 execute() API 传递实际值。

These two methods can be used to pass bind values to SQL statements. There may be a case when values to be entered is not given in advance. In such a case, binding values are used. A question mark (?) is used in place of actual values and then actual values are passed through execute() API.

以下是 EMPLOYEE 表中创建两条记录的示例 −

Following is the example to create two records in the EMPLOYEE table −

#!/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 server
   dbh.disconnect if dbh
end

如果一次有多个 INSERT,那么先准备一条语句,然后在循环中多次执行它比每次通过循环来调用 do 更有效率。

If there are multiple INSERTs at a time, then preparing a statement first and then executing it multiple times within a loop is more efficient than invoking do each time through the loop.

READ Operation

在任何数据库上进行 READ 操作意味着从数据库中获取一些有用的信息。

READ Operation on any database means to fetch some useful information from the database.

一旦建立我们的数据库连接,我们就可以对该数据库进行查询。我们可以使用 do 方法或 prepareexecute 方法从数据库表中获取值。

Once our database connection is established, we are ready to make a query into this database. We can use either do method or prepare and execute methods to fetch values from a database table.

记录获取需要以下步骤 −

Record fetching takes following steps −

  1. Preparing SQL query based on required conditions. This will be done using the prepare method.

  2. Executing SQL query to select all the results from the database. This will be done using the execute method.

  3. Fetching all the results one by one and printing those results. This will be done using the fetch method.

  4. Releasing Statement handle. This will be done using the finish method.

以下是在 EMPLOYEE 表中查询薪水超过 1000 的所有记录的过程。

Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000.

#!/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 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

还有更简单的快捷方式来从数据库中获取记录。如果感兴趣,请浏览 Fetching the Result ,否则继续下一部分。

There are more short cut methods to fetch records from the database. If you are interested then go through the Fetching the Result otherwise proceed to the next section.

Update Operation

对任何数据库上的 UPDATE 操作意味着更新数据库中已有的一个或多个记录。以下是在 SEX 为 'M' 的情况下更新所有记录的过程。在这里,我们将所有男性的 AGE 增加一年。这需要三个步骤 −

UPDATE Operation on any database means to update one or more records, which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here, we will increase AGE of all the males by one year. This will take three steps −

  1. Preparing SQL query based on required conditions. This will be done using the prepare method.

  2. Executing SQL query to select all the results from the database. This will be done using the execute method.

  3. Releasing Statement handle. This will be done using the finish method.

  4. If everything goes fine then commit this operation otherwise you can rollback the complete transaction.

#!/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 server
   dbh.disconnect if dbh
end

DELETE Operation

当您想从数据库中删除某些记录时,需要 DELETE 操作。以下是删除 EMPLOYEE 表中 AGE 大于 20 的所有记录的过程。此操作将执行以下步骤。

DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20. This operation will take following steps.

  1. Preparing SQL query based on required conditions. This will be done using the prepare method.

  2. Executing SQL query to delete required records from the database. This will be done using the execute method.

  3. Releasing Statement handle. This will be done using the finish method.

  4. If everything goes fine then commit this operation otherwise you can rollback the complete transaction.

#!/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 server
   dbh.disconnect if dbh
end

Performing Transactions

事务是一种确保数据一致性的机制。事务应当有以下四种属性 −

Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties −

  1. Atomicity − Either a transaction completes or nothing happens at all.

  2. Consistency − A transaction must start in a consistent state and leave the system is a consistent state.

  3. Isolation − Intermediate results of a transaction are not visible outside the current transaction.

  4. Durability − Once a transaction was committed, the effects are persistent, even after a system failure.

DBI 提供两种方法来提交或回滚交易。还有一个名为事务的方法,可用于实施事务。有两种简单方法来实施事务 -

The DBI provides two methods to either commit or rollback a transaction. There is one more method called transaction which can be used to implement transactions. There are two simple approaches to implement transactions −

Approach I

第一种方法使用 DBI 的 commit 和 rollback 方法来明确提交或取消事务 -

The first approach uses DBI’s commit and rollback methods to explicitly commit or cancel the transaction −

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

Approach II

第二种方法使用事务方法。这更简单,因为它采用包含构成事务的语句的代码块。事务方法执行代码块,然后根据代码块是否成功或失败,自动调用 commit 或 rollback -

The second approach uses the transaction method. This is simpler, because it takes a code block containing the statements that make up the transaction. The transaction method executes the block, then invokes commit or rollback automatically, depending on whether the block succeeds or fails −

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 the operation, which gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.

下面是一个调用 commit 方法的简单示例。

Here is a simple example to call the commit method.

dbh.commit

ROLLBACK Operation

如果你对一项或多项更改不满意,并且希望完全撤销这些更改,那么请使用 rollback 方法。

If you are not satisfied with one or more of the changes and you want to revert back those changes completely, then use the rollback method.

下面是一个调用 rollback 方法的简单示例。

Here is a simple example to call the rollback method.

dbh.rollback

Disconnecting Database

要断开数据库连接,请使用断开连接 API。

To disconnect Database connection, use disconnect API.

dbh.disconnect

如果用户使用断开连接方法关闭与数据库的连接,DBI 会回滚所有未完成的事务。但是,与其依赖于 DBI 的任何实施细节,你的应用程序最好明确调用 commit 或 rollback。

If the connection to a database is closed by the user with the disconnect method, any outstanding transactions are rolled back by the DBI. However, instead of depending on any of DBI’s implementation details, your application would be better off calling the commit or rollback explicitly.

Handling Errors

有许多错误来源。一些示例是已执行 SQL 语句中的语法错误、连接故障或对已取消或完成的语句句柄调用获取方法。

There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.

如果 DBI 方法失败,DBI 会引发异常。DBI 方法可能会引发任何几种类型的异常,但最重要的两个异常类是 DBI::InterfaceError 和 DBI::DatabaseError。

If a DBI method fails, DBI raises an exception. DBI methods may raise any of several types of exception but the two most important exception classes are DBI::InterfaceError and DBI::DatabaseError.

这些类的异常对象有三个属性,分别名为 err、errstr 和 state,表示错误号、描述性错误字符串和标准错误代码。这些属性的解释如下 -

Exception objects of these classes have three attributes named err, errstr, and state, which represent the error number, a descriptive error string, and a standard error code. The attributes are explained below −

  1. err − Returns an integer representation of the occurred error or nil if this is not supported by the DBD.The Oracle DBD for example returns the numerical part of an ORA-XXXX error message.

  2. errstr − Returns a string representation of the occurred error.

  3. state − Returns the SQLSTATE code of the occurred error.The SQLSTATE is a five-character-long string. Most DBDs do not support this and return nil instead.

你一定在大多数示例中看到了上面的代码 -

You have seen following code above in most of the examples −

rescue DBI::DatabaseError => e
   puts "An error occurred"
   puts "Error code:    #{e.err}"
   puts "Error message: #{e.errstr}"
   dbh.rollback
ensure
   # disconnect from server
   dbh.disconnect if dbh
end

要获取有关你的脚本在执行时正在进行的操作的调试信息,你可以启用跟踪。要做到这一点,你必须首先加载 dbi/trace 模块,然后调用控制跟踪模式和输出目的地的 trace 方法 -

To get debugging information about what your script is doing as it executes, you can enable tracing. To do this, you must first load the dbi/trace module and then call the trace method that controls the trace mode and output destination −

require "dbi/trace"
..............

trace(mode, destination)

模式值可以是 0(关闭)、1、2 或 3,目标应该是 IO 对象。默认值分别是 2 和 STDERR。

The mode value may be 0 (off), 1, 2, or 3, and the destination should be an IO object. The default values are 2 and STDERR, respectively.

Code Blocks with Methods

有一些方法可以创建句柄。这些方法可以通过代码块来调用。使用代码块和方法一起的优点是,它们将句柄作为其参数传递给代码块,并在代码块终止时自动清除句柄。以下有几个理解这个概念的示例。

There are some methods that create handles. These methods can be invoked with a code block. The advantage of using code block along with methods is that they provide the handle to the code block as its parameter and automatically cleans up the handle when the block terminates. There are few examples to understand the concept.

  1. DBI.connect − This method generates a database handle and it is recommended to call disconnect at the end of the block to disconnect the database.

  2. dbh.prepare − This method generates a statement handle and it is recommended to finish at the end of the block. Within the block, you must invoke execute method to execute the statement.

  3. dbh.execute − This method is similar except we don’t need to invoke execute within the block. The statement handle is automatically executed.

Example 1

DBI.connect 可以获取代码块,向数据库句柄传递代码块,然后在代码块的末尾自动断开与句柄的连接,如下所示。

DBI.connect can take a code block, passes the database handle to it, and automatically disconnects the handle at the end of the block as follows.

dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", "testuser", "test123") do |dbh|

Example 2

dbh.prepare 可以获取代码块,向语句句柄传递代码块,然后在代码块的末尾自动调用完成方法,如下所示。

dbh.prepare can take a code block, passes the statement handle to it, and automatically calls finish at the end of the block as follows.

dbh.prepare("SHOW DATABASES") do |sth|
   sth.execute
   puts "Databases: " + sth.fetch_all.join(", ")
end

Example 3

dbh.execute 可以获取代码块,向语句句柄传递代码块,然后在代码块的末尾自动调用完成方法,如下所示 −

dbh.execute can take a code block, passes the statement handle to it, and automatically calls finish at the end of the block as follows −

dbh.execute("SHOW DATABASES") do |sth|
   puts "Databases: " + sth.fetch_all.join(", ")
end

DBI 事务方法还会获取上面描述的代码块。

DBI transaction method also takes a code block which has been described in above.

Driver-specific Functions and Attributes

使用 DBI,数据库驱动程序可以提供其他特定于数据库的功能,用户可以通过任何句柄对象的 func 方法调用这些函数。

The DBI lets the database drivers provide additional database-specific functions, which can be called by the user through the func method of any Handle object.

支持特定于驱动程序的属性,可以使用 []=[] 方法设置或获取这些属性。

Driver-specific attributes are supported and can be set or gotten using the []= or [] methods.

Example

#!/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