Class: JDBC::Result
- Inherits:
-
Object
- Object
- JDBC::Result
- Defined in:
- lib/jdbc/result.rb
Overview
Result wraps a java ResultSet, and provides methods to both fetch rows one at a time, as well as ruby iterators. All rows are automatically converted to a ruby Array or Hash when they are fetched. Each column is casted to the equivalent ruby object if possible, otherwise it will be a String.
Instance Method Summary collapse
-
#close ⇒ Object
Closes the Result.
-
#each ⇒ Object
Returns each row as an Array to the provided block.
-
#each_hash ⇒ Object
Returns each row as an Hash to the provided block.
-
#fetch ⇒ Object
Fetches the next row and returns it as an Array.
-
#fetch_hash ⇒ Object
Fetches the next row and returns it as a Hash.
-
#initialize(resultSet, statement) ⇒ Result
constructor
Takes a java ResultSet and Statement.
Constructor Details
#initialize(resultSet, statement) ⇒ Result
Takes a java ResultSet and Statement. You should not have to call this. A Result will usually be instantiated by a DB or PreparedStatement.
10 11 12 13 14 |
# File 'lib/jdbc/result.rb', line 10 def initialize(resultSet, statement) @rs = resultSet @stmt = statement @columns = end |
Instance Method Details
#close ⇒ Object
Closes the Result
74 75 76 77 |
# File 'lib/jdbc/result.rb', line 74 def close @rs.close unless @rs.nil? @stmt.close unless @stmt.nil? end |
#each ⇒ Object
Returns each row as an Array to the provided block. Will automatically close the Result after the block exits.
59 60 61 62 63 |
# File 'lib/jdbc/result.rb', line 59 def each while(result = fetch) yield(result) end end |
#each_hash ⇒ Object
Returns each row as an Hash to the provided block. The column names are the keys. Will automatically close the Result after the block exits.
67 68 69 70 71 |
# File 'lib/jdbc/result.rb', line 67 def each_hash while(result = fetch_hash) yield(result) end end |
#fetch ⇒ Object
Fetches the next row and returns it as an Array. Returns nil if no more rows are available and closes the Result.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/jdbc/result.rb', line 18 def fetch if @rs.next result = [] @columns.each do |column| result << fetch_and_cast(@rs, column) end return result end close return nil end |
#fetch_hash ⇒ Object
Fetches the next row and returns it as a Hash. The column names are the keys. Returns nil is no more rows are available and closes the Result.
Note: All column names are automatically lowercased for consistency since databases differ in behavior on this aspect. (ex: Derby is uppercase, Postgres is lowercase, and Mysql depends on how the table was created.)
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/jdbc/result.rb', line 41 def fetch_hash if @rs.next result = {} @columns.each do |column| result[column[:name]] = fetch_and_cast(@rs, column) end return result end close return nil end |