如何在JDBCTemplate spring 4中打开数据库连接

时间:2017-06-08 06:43:45

标签: java spring-mvc jdbctemplate

我在spring4中使用JDBCTemplate来执行返回Blob对象的select查询。现在我尝试使用以下代码将Blob对象转换为字符串

Blob image;  
ImageScanningBean imageScanningBean = new ImageScanningBean();  
image = rs.getBlob("IMAGEOUT");  
StringBuffer strOut = new StringBuffer();  
try
{  
    String aux;  
   BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));  
   while ((aux=br.readLine())!=null) 
   {  
        strOut.append(aux);
   }  
   strOut.toString();  
   imageScanningBean.setImageOutBase64(strOut.toString());  
}  
 catch(Exception e){
   e.printStackTrace();
}

但是我在接下来的行中收到错误,因为连接已关闭

BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));

如何在JDBCTemplate中打开数据库连接

1 个答案:

答案 0 :(得分:0)

在我使用queryForObject()之前,它在操作完成时自动关闭连接     bean = jdbcTemplate.queryForObject(" select * from tablename",new Object [] {tokenId,tellerId},new BeanPropertyRowMapper(TokenDetailsBean.class));

所以为了保持连接活着,我刚刚添加了mapRow()

try
    {
        imageScanningBean = jdbcTemplate.queryForObject("select * from tablename", new Object[]{imageScanningBean.getTellerId()},new BeanPropertyRowMapper<ImageScanningBean>(){
            public ImageScanningBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                Blob image;
                ImageScanningBean imageScanningBean = new ImageScanningBean();
                image = rs.getBlob("IMAGEOUT");
                StringBuffer strOut = new StringBuffer();
                try
                {
                    String aux;
                    BufferedReader br = new BufferedReader(new InputStreamReader(image.getBinaryStream()));
                    while ((aux=br.readLine())!=null) 
                    {
                        strOut.append(aux);
                    }
                    strOut.toString();
                    imageScanningBean.setImageOutBase64(strOut.toString());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
                return imageScanningBean;
            }
        });
    } 
    catch(EmptyResultDataAccessException er)
    {
        er.printStackTrace();
        return imageScanningBean;
    }