Skip to content

Instantly share code, notes, and snippets.

@rwjblue
Created November 15, 2011 03:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rwjblue/1366047 to your computer and use it in GitHub Desktop.
Save rwjblue/1366047 to your computer and use it in GitHub Desktop.
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
Copy link

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

@nathanchilton
Copy link

It's amazing to me that this code still works, a dozen years later!

I just had to update two things:

  • change meta.column_name to meta.get_column_name
  • change meta.column_type to meta.get_column_type

Thank you, @rwjblue !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment