Ruby DBI Read Operations
DBI provides several different ways to fetch records from a database. Assumedbhis a database handle,sthis a statement handle:
| No. | Method & Description |
|---|---|
| 1 | db.select_one( stmt, *bindvars ) => aRow | nil Executes the statement withbindvarsbound before the parameter markersstmtstatement. Returns the first row; if the result set is empty, returnsnil。 |
| 2 | db.select_all( stmt, *bindvars ) => [aRow, ...] | nil db.select_all( stmt, *bindvars ){ |aRow| aBlock } Executes the statement withbindvarsbound before the parameter markersstmtstatement. Called without a block, this method returns an array containing all rows. If a block is given, it is called for each row. |
| 3 | sth.fetch => aRow | nil Returnsthe next row. If there is no next row in the result, returnsnil。 |
| 4 | sth.fetch { |aRow| aBlock } Calls the given block for the remaining rows in the result set. |
| 5 | sth.fetch_all => [aRow, ...] Returns all remaining rows of the result set stored in an array. |
| 6 | sth.fetch_many( count ) => [aRow, ...] Returns the offset-th row down, stored in the [aRow, ...] arraycountrow. |
| 7 | sth.fetch_scroll( direction, offset=1 ) => aRow | nil Returnsdirectionthe parameter andoffsetspecified row. Except for SQL_FETCH_ABSOLUTE and SQL_FETCH_RELATIVE, all other methods discard the parameteroffset。directionThe possible values for the parameter are given in the following table. |
| 8 | sth.column_names => anArray Returns the names of the columns. |
| 9 | column_info => [ aColumnInfo, ... ] Returns an array of DBI::ColumnInfo objects. Each object stores information about a column and contains the column's name, type, precision, and other additional information. |
| 10 | sth.rows => rpc Returns the number of rows processed by the statementCount, if there is no such number, returnsnil。 |
| 11 | sth.fetchable? => true | false If rows can be fetched, returnstrue, otherwise returnsfalse。 |
| 12 | sth.cancel Releases the resources held by the result set. After calling this method, you can no longer fetch rows unless you call againexecute。 |
| 13 | sth.finish Releases the resources held by the prepared statement. After calling this method, you cannot call any further operation methods on this object. |
direction parameter
The following values can be used for thefetch_scrollmethod's direction parameter:
| Constant | Description |
|---|---|
| DBI::SQL_FETCH_FIRST | Fetches the first row. |
| DBI::SQL_FETCH_LAST | Fetches the last row. |
| DBI::SQL_FETCH_NEXT | Fetches the next row. |
| DBI::SQL_FETCH_PRIOR | Fetches the previous row. |
| DBI::SQL_FETCH_ABSOLUTE | Fetches the row at the specified offset. |
| DBI::SQL_FETCH_RELATIVE | Fetches the row at the specified offset from the current row. |
Examples
The following example demonstrates how to fetch the metadata of a statement. Assume we have an EMPLOYEE table.
#!/usr/bin/ruby -w
require "dbi"
begin
# 连接到 MySQL 服务器
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
# 断开与服务器的连接
dbh.disconnect if dbh
end
This will produce the following result:
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: 32768Other Extensions