java使用jdbcTemplate操作mysql数据库,遇到blob字段,正常读取出来是blob的地址,而不是blob的内容。
下面采用2中方式读取blob的内容:
1、以二进制数组形式读取blob,适用于文本数据
public void testJdbc()
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("restlet-servlet.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate)ctx.getBean("jdbcTemplate");
String sql = "select * from violation_redis t where t.id < 10";
final LobHandler lobHandler=new DefaultLobHandler();
@SuppressWarnings("unchecked")
List<Map<String,String>> list = jdbcTemplate.query(sql,new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException
{
//以二进制的数组方式获得Blob数据,第二个参数3是指blob字段在结果集的位置
byte[] attach = lobHandler.getBlobAsBytes(rs, 3);
//非blob子弹获取
String key = rs.getString("vio_key");
String strAttach = new String(attach);
p(key + "==" + strAttach);
Map<String,String> map = new HashMap<String,String>();
map.put("vio_key", key);
map.put("vio_info", strAttach);
return map;
}
});
p(list);
}
2、流模式读取blob:
public void getBlob(OutputStream out)
{
String sql = "select * from violation_redis t where t.id < 10";
final LobHandler lobHandler=new DefaultLobHandler();
List<Map<String,String>> list = jdbcTemplate.query(sql,new RowMapper(){
public Object mapRow(ResultSet rs, int rowNum) throws SQLException
{
//以二进制的数组方式获得Blob数据
InputStream is = lobHandler.getBlobAsBinaryStream(rs, 2);
if(is != null){
//利用spring的工具类将输入流的数据复制到输出流中
FileCopyUtils.copy(is, out);
}
});
}