When is it safe to close the InputStream used by PreparedStatement.setBlob?

PreparedStatement.setBlob,, PreparedStatement.setBinaryStreamand several other methods PreparedStatementcan read data for a request from InputStream. Unfortunately, the documentation is not entirely clear when reading data. All he says is that

data will be read from the stream as needed until the end of the file is reached.

I can imagine three possible interpretations when data is needed:

  • Before calling setBlob (or another method that has a parameter InputStream) returns
  • When the statement is executed
  • When making a transaction

So, at what point is it safe to close InputStream(or other resources that the question depends on InputStream)? It depends on the driver (I am currently using it MySQL, but since I like to open the possibility of migration, it would be nice to know how other drivers do this)?

+3
source share
1 answer

Wrote a quick example to check this locally with MySQL (sorry for the incorrect exception handling):

public void testInputStream(String filePath) throws SQLException, IOException {
    DBUtil util = new DBUtil();//just a simple connection util
    Connection conn = util.getConnection("test");

    conn.setAutoCommit(false);

    File file = new File(filePath);
    FileInputStream fis = null;

    fis = new FileInputStream(file);

    String sql = "insert into testtable(scol,lob) values(?,?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "number4!");
    stmt.setBlob(2, fis);
    //fis.close() //this throws an exception
    stmt.executeUpdate();
    fis.close();//no exception here
    conn.commit();
    //fis.close();//no exception when called here
    stmt.close();
}

testtable is a very simple table:

create table testtable (
    id int auto_increment primary key,
    scol varchar(50),
    lob blob
)engine=innodb;

, , . , , , , InputStream . MySQL PreparedStatement ; , sendPacket() ( , ), executeUpdate() .

, , , JDBC. , InputStream, .

+2

All Articles