I'm having trouble reading MySQL VARBINARY as a string using JdbcTemplate. We store line abbreviations ("ABC", "XYZ", "LMN", etc.) as VARBINARY (don't ask me why). Oddly enough, when I use the Connection / PreparedStatement route and the plain old ResultSets vs. SqlRowSet, I have no problem reading the string. I.e
This code works:
String sql = "select MY_VARBINARY_FIELD from MY_TABLE where KEY1=? and KEY2=?"; PreparedStatement stmt = connectionDev.prepareStatement(sql); prepStmt1.setInt(1, key1); prepStmt1.setInt(2, key2); ResultSet rs = stmt.executeQuery(); while (rs.next()) { String s = rs.getString("MY_VARBINARY_FIELD"); System.out.print(s + " "); } **Output:** AHI-1 DKFZp686J1653 FLJ14023 FLJ20069 JBTS3 ORF1 dJ71N10.1
But this code does not:
String sql = "select MY_VARBINARY_FIELD from MY_TABLE where KEY1=? and KEY2=?"; Object[] params = {key1, key2}; SqlRowSet rows = getJdbcTemplate().queryForRowSet(sql, params); while (rows.next()) { String s = rows.getString("MY_VARBINARY_FIELD"); System.out.print(s + " "); } **Output:** [ B@3a329572 [ B@4ef18d37 [ B@546e3e5e [ B@11c0b8a0 [ B@399197b [ B@3857dc15 [ B@10320399
Why are SqlRowSet and ResultSet creating a different string representation for VARBINARY? And how can I get the βcorrectβ view using JdbcTemplate / SqlRowSet?
Thanks!
Decision
Mark Rottweel (below) answered the question. I got this to work with this:
String sql = "select MY_VARBINARY from MY_TABLE where KEY=VALUE"; SqlRowSet rows = getJdbcTemplate().queryForRowSet(sql); while (rows.next()) { byte[] varbinary = (byte[]) rows.getObject("MY_VARBINARY"); System.out.println(new String(varbinary)); }
ktm5124
source share