【问题标题】:Connection Closed error on querying BLOBs from JdbcTemplate从 JdbcTemplate 查询 BLOB 时出现连接关闭错误
【发布时间】:2020-01-11 21:58:47
【问题描述】:

我正在从数据库中查询一个 BLOB 对象并尝试将其写入文件系统,但我一直遇到连接关闭错误。这是代码

FileOutputStream out;

out = new FileOutputStream(filePathtoCreate+File.separator+filename);

        Blob inBlob= jdbcTemplate.queryForObject("select BLOB_CONTENT from Table_A where name = ?" , Blob.class,new Object[] { filename});
        InputStream in = inBlob.getBinaryStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        } catch (SQLException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

当我运行这段代码时,我得到了

java.sql.SQLRecoverableException: Closed Connection
    at oracle.sql.BLOB.getDBAccess(BLOB.java:1122)
    at oracle.sql.BLOB.getBinaryStream(BLOB.java:265)

如果我使用常规 JDBC 连接,我不会遇到此问题,那么为什么会发生这种情况以及如何解决它。提前致谢。

【问题讨论】:

    标签: java spring jdbc blob jdbctemplate


    【解决方案1】:

    您可以在jdbcTemplate's query with RowMapperexample 中读取 Blob:

    jdbcTemplate.query("select * from Report where id =?",
                  new Object[]{id}, (resultSet, i) -> {
                      return toReport(resultSet);
                  });
    
    private Report toReport(ResultSet resultSet) throws SQLException {
      InputStream contentStream = resultSet.getClob("CONTENT")
                                           .getAsciiStream();
      String content =
              new Scanner(contentStream, "UTF-8").useDelimiter("\\A").next();
      report.setContent(content);
      Blob blob = resultSet.getBlob("IMAGE");
    

    查询给定的 SQL 以从 SQL 中创建准备好的语句和要绑定到查询的参数列表,通过 RowMapper 将每一行映射到结果对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 2016-03-13
      相关资源
      最近更新 更多