Skip to content

Instantly share code, notes, and snippets.

@bf4 bf4/jdbc_sample.rb forked from rwjblue/jdbc_sample.rb
Created Apr 18, 2018

Embed
What would you like to do?
Convert JDBC ResultSet into Ruby Hash with JRuby
require './lib/adsjdbc-10.10.0.28.jar'
java_import java.sql.Driver
java_import java.sql.DriverManager
java_import 'com.extendedsystems.jdbc.advantage.ADSDriver'
class AdsAdapter
def initialize(connect_string)
@connect_string = connect_string
end
def establish_connection(connect_string = @connect_string)
::DriverManager.getConnection(connect_string)
end
def connection
@connection ||= establish_connection
end
def execute(sql)
stmt = connection.createStatement
rs = stmt.executeQuery(sql)
resultset_to_hash(rs)
ensure
stmt.close if stmt
end
def resultset_to_hash(resultset)
rows = []
while resultset.next
rows << row_to_hash(resultset)
end
rows
end
def row_to_hash(resultset)
column_count = resultset.meta_data.column_count
row = {}
(1..column_count).each do |column_index|
name = get_column_name(resultset, column_index)
value = get_column_value(resultset, column_index)
row[name] = value
end
row
end
def inspect_column(resultset, column_index)
meta = resultset.meta_data
[
meta.get_column_type_name(column_index),
meta.get_column_name(column_index),
meta.get_column_label(column_index),
meta.get_column_class_name(column_index),
meta.get_column_display_size(column_index),
meta.get_column_type(column_index)
]
end
def get_column_name(resultset, column_index)
resultset.meta_data.get_column_name(column_index)
end
# https://gist.github.com/rwjblue/1366047
def get_column_value(resultset, column_index)
meta = resultset.meta_data
case meta.get_column_type(column_index)
when -6, -5, 5, 4 # TINYINT, BIGINT, INTEGER
resultset.get_int(column_index).to_i
when 41, 91 # Date
resultset.get_date(column_index)&.toString
when 92 # Time
resultset.get_time(column_index).toString
when 93 # Timestamp
resultset.get_timestamp(column_index)&.toString
when 2, 3, 6 # NUMERIC, DECIMAL, FLOAT
if meta.get_scale(column_index).zero?
resultset.get_long(column_index).to_i
else
resultset.get_string(column_index).to_s.to_f
end
when 1, -15, -9, 12
# CHAR, NCHAR, NVARCHAR, VARCHAR
resultset.get_string(column_index).to_s
when 8 # [Double, double]
resultset.get_string(column_index).to_s
when -7 # Logical, boolean
resultset.get_string(column_index).to_s
else
p [:unknown, inspect_column(resultset, column_index)]
resultset.get_string(column_index).to_s
end
end
end
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.