English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby DBI Read Operation

DBI provides various methods for retrieving records from a database. Suppose dbh Is a database handle,sth Is a statement handle:

Serial NumberMethod & Description
1db.select_one( stmt, *bindvars ) => aRow | nil
Execute with bindvars Bound before the parameter marker stmt statement. Return the first row, or return nil.
2db.select_all( stmt, *bindvars ) => [aRow, ...] | nil
db.select_all( stmt, *bindvars ){ |aRow| aBlock }

Execute with bindvars Bound before the parameter marker stmt statement. Calling this method without a block returns an array containing all rows. If a block is given, the method will be called for each row.
3sth.fetch => aRow | nil
returnthe next row. If there is no next row in the result, return nil.
4sth.fetch { |aRow| aBlock }
Call the given block for the remaining rows in the result set.
5sth.fetch_all => [aRow, ...]
Return all remaining rows in the result set stored in the array.
6sth.fetch_many( count ) => [aRow, ...]
Return the downward row number in the array [aRow, ...]. count row.
7sth.fetch_scroll( direction, offset=1 ) => aRow | nil
return direction parameters and offset The specified row. All other methods except SQL_FETCH_ABSOLUTE and SQL_FETCH_RELATIVE will discard the parameters offset.direction Possible values of the parameter, please see the table below.
8sth.column_names => anArray
Return the name of the column.
9column_info => [ aColumnInfo, ... ]
Return an array of DBI::ColumnInfo objects. Each object stores information about a column, including the column name, type, precision, and other more information.
10sth.rows => rpc
Return the number of rows processed by the execution statement Countif it does not exist, return nil.
11sth.fetchable? => true | false
Return trueotherwise return false.
12sth.cancel
Release the resources occupied by the result set. After calling this method, you cannot get rows anymore unless you call execute.
13sth.finish
Release the resources occupied by the prepared statement. After calling this method, you cannot call other further operation methods on the object.

direction parameter

The following values can be used fetch_scroll The direction parameter of the method:

ConstantDescription
DBI::SQL_FETCH_FIRSTGet the first row.
DBI::SQL_FETCH_LASTGet the last row.
DBI::SQL_FETCH_NEXTGet the next row.
DBI::SQL_FETCH_PRIORGet the previous row.
DBI::SQL_FETCH_ABSOLUTEGet the row at the offset position.
DBI::SQL_FETCH_RELATIVEGet the number of rows offset from the current row.

Online Example

The following example demonstrates how to retrieve metadata for a statement. Assume we have an EMPLOYEE table.

#!/usr/bin/ruby -w
require "dbi"
begin
     # Connect to MySQL server
     dbh = DBI.connect("DBI:Mysql:TESTDB:localhost", 
                        "testuser", "test123")
     sth = dbh.prepare("SELECT * FROM EMPLOYEE 
                        WHERE INCOME > ?")
     sth.execute(1000)
     if sth.column_names.size == 0 then
        puts "Statement has no result set"
        printf "Number of rows affected: %d\n", sth.rows
     else
        puts "Statement has a result set"
        rows = sth.fetch_all
        printf "Number of rows: %d\n", rows.size
        printf "Number of columns: %d\n", sth.column_names.size
        sth.column_info.each_with_index do |info, i|
          printf ""--- Column %d (%s) ---\n, i, info["name"]
          printf "sql_type:                         %s\n", info["sql_type"]
          printf "type_name:        %s\n", info["type_name"]
          printf "precision:        %s\n", info["precision"]
          printf "scale:            %s\n", info["scale"]
          printf "nullable:         %s\n", info["nullable"]
          printf "indexed:          %s\n", info["indexed"]
          printf "primary:          %s\n", info["primary"]
          printf "unique:           %s\n", info["unique"]
          printf "mysql_type:       %s\n", info["mysql_type"]
          printf "mysql_type_name:  %s\n", info["mysql_type_name"]
          printf "mysql_length:     %s\n", info["mysql_length"]
          printf "mysql_max_length: %s\n", info["mysql_max_length"]
          printf "mysql_flags:      %s\n", info["mysql_flags"]
      end
   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 results:

Statement has a result set
Number of rows: 5
Number of columns: 5
--- Column 0 (FIRST_NAME) ---
sql_type:         12
type_name:        VARCHAR
precision:        20
scale:            0
nullable:          true
indexed:          false
primary:          false
unique:           false
mysql_type:       254
mysql_type_name:  VARCHAR
mysql_length:     20
mysql_max_length: 4
mysql_flags:      0
--- Column 1 (LAST_NAME) ---
sql_type:         12
type_name:        VARCHAR
precision:        20
scale:            0
nullable:          true
indexed:          false
primary:          false
unique:           false
mysql_type:       254
mysql_type_name:  VARCHAR
mysql_length:     20
mysql_max_length: 5
mysql_flags:      0
--- Column 2 (AGE) ---
sql_type:         4
type_name:        INTEGER
precision:        11
scale:            0
nullable:          true
indexed:          false
primary:          false
unique:           false
mysql_type:       3
mysql_type_name:  INT
mysql_length:     11
mysql_max_length: 2
mysql_flags:      32768
--- Column 3 (SEX) ---
sql_type:         12
type_name:        VARCHAR
precision:        1
scale:            0
nullable:          true
indexed:          false
primary:          false
unique:           false
mysql_type:       254
mysql_type_name:  VARCHAR
mysql_length:     1
mysql_max_length: 1
mysql_flags:      0
--- Column 4 (INCOME) ---
sql_type:         6
type_name:        FLOAT
precision:        12
scale:            31
nullable:          true
indexed:          false
primary:          false
unique:           false
mysql_type:       4
mysql_type_name:  FLOAT
mysql_length:     12
mysql_max_length: 4
mysql_flags:      32768