I’ve started using jruby more and more, but I’m a bit unsatisfied by the current status of mysql support, the jdbc api is a bit cumbersome to me (of course only after getting lazy because of the convenience of the original ruby mysql gem) – especially about SELECTs and using their result set. Thus, I wrote a small callback wrapper, see below:
require 'jdbc/mysql' require 'java' $KCODE = "u" class MySQL def initialize(dbhost, user, pass, db, encoding="UTF8") Java::com.mysql.jdbc.Driver userurl = "jdbc:mysql://#{dbhost}/#{db}" @connSelect = java.sql.DriverManager.get_connection(userurl, user, pass) @stmtSelect = @connSelect.create_statement @stmtSelect.execute_query("SET NAMES #{encoding}") @stmtSelect.execute_query("SET CHARACTER SET #{encoding}") end def query(querystr) res = @stmtSelect.execute_query(querystr) meta = res.getMetaData colcnt = meta.getColumnCount names = {} colcnt.times {|i| names[i+1] = meta.getColumnName(i+1) } while (res.next) do row = {} colcnt.times {|i| row[names[i+1]]= res.getString(i+1) } yield row end end end sql = MySQL.new('127.0.0.1', 'root', nil, 'whatever') qstring = "SELECT something1, something2 FROM MyCoolTable" sql.query(qstring){ |row| pp row # this is a hash keyed by the column names } |
I hacked this together in 5 minutes, I’m sure there’s much room for improvement

Facebook
Google
LinkedIn
Twitter
RSS