Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert JDBC ResultSet into Ruby Hash with JRuby
require 'java'
require 'jt400'
require 'date'
require 'bigdecimal'
java_import 'com.ibm.as400.access.AS400JDBCDriver'
def get_records
@connection ||= java.sql.DriverManager.get_connection("jdbc:as400://127.0.0.1/",'username','password')
rs = @connection.createStatement.executeQuery("SELECT * FROM RANDOM_TABLE")
puts resultset_to_hash(rs).inspect
end
def resultset_to_hash(resultset)
meta = resultset.meta_data
rows = []
while resultset.next
row = {}
(1..meta.column_count).each do |i|
name = meta.column_name i
row[name] = case meta.column_type(i)
when -6, -5, 5, 4
# TINYINT, BIGINT, INTEGER
resultset.get_int(i).to_i
when 41
# Date
resultset.get_date(i)
when 92
# Time
resultset.get_time(i).to_i
when 93
# Timestamp
resultset.get_timestamp(i)
when 2, 3, 6
# NUMERIC, DECIMAL, FLOAT
case meta.scale(i)
when 0
resultset.get_long(i).to_i
else
BigDecimal.new(resultset.get_string(i).to_s)
end
when 1, -15, -9, 12
# CHAR, NCHAR, NVARCHAR, VARCHAR
resultset.get_string(i).to_s
else
resultset.get_string(i).to_s
end
end
rows << row
end
rows
end
@greghelton

This comment has been minimized.

Copy link

commented Sep 3, 2014

Your code for converting resultset to hash helped a lot. I have a JRuby+Sinatra+AS400 example @ http://opensourcetips.blogspot.com/2014/09/datatablesnet-jruby-sinatra.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.