日期:2014-05-16  浏览次数:20538 次

Hibernate操作Blob,将Blob转换为String
public String getScenicCoord(String pk) {
    log.debug("根据景区唯一标示获取景区坐标!");
    String sql = "select wkt from JQGEO where id = '" + pk + "'";
    String result = "";
    try {
    Connection conn = getSession().connection();
    PreparedStatement ps = conn.prepareStatement(sql);
    ResultSet set = ps.executeQuery();
    if(set.next()) {
    Blob blob = set.getBlob(1);
    //这种方式看起来没有什么问题,但是数据类型及参数未知的错误会在莫名的情况下出现
    //int len = (int)blob.length();
    //byte[] bt = blob.getBytes(0, len);
    //String str = new String(bt);
   
    //这种转换后的方式倒是能够正常的将二进制流转换为String类型数据
    InputStream in = blob.getBinaryStream();
    int size = in.available();
    byte[] by = new byte[size];
    in.read(by);
    result = new String(by);
    }
    }catch (Exception e) {
log.error("根据景区唯一标示获取景区坐标失败!");
result = null;
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
result = null;
}
}
    return result;
    }