JDBC插入后BLOB列为空

时间:2014-06-19 15:18:48

标签: java oracle jdbc blob

我有这个代码(实际上,这是它的简化版本,obv。)

private StreamAndStatement getStatement(File f, String fid, Long dex, String uid, int id)
{
  FileInputStream fis = null;
  PreparedStatement statement;
  statement = connection.prepareStatement("INSERT INTO BLOBTABLE (FID, FDEX, SFILE, UID, ID) VALUES (?, ?, ?, ?, ?)");
  statement.setString(1, fid);
  statement.setLong(2, dex);
  fis = new FileInputStream(file);
  statement.setBinaryStream(3, fis, file.length());
  statement.setString(4, uid);
  statement.setInt(5, id);

  return new StreamAndStatement(statement, fis);
}

private insertStuff()
{
  File f = new File("/home/user/thisFileExists");
  StreamAndStatement sAndStatement = getStatement(f, "XYZ", 18L, "ABC", 78);
  sAndStatement.getStatement().execute();
  sAndStatement.closeStream();
}

StreamAndStatement和您想象的一样简单明了。

现在整个代码在没有Oracle对我大喊大叫的情况下运行但是blob刚刚结束了......

我真的没有在它之间的任何一点搞乱流,如你所见,创建流的getStatement和语句的执行是连续两行,所以没有篡改......

1 个答案:

答案 0 :(得分:0)

我们首先使用空blob插入记录,然后我们进入更新模式设置其内容。据我所知,这是经典的方法。代码可以如下(DbUtil给我们一些实用方法):

    int insertBlobGettingId(Connection con, int idUpload, InputStream streamFile) {
            int idBlob = DBUtil.getUniqueIdentifier("seq_uploaded_blob", con);
            String insertEmptyBlob = "insert into uploaded_blob (id, FILE_CONTENT) values ("+idBlob+", empty_blob())";
            DBUtil.executeSql(insertEmptyBlob, con);

            if(streamFile != null) {
                String sql = "select file_content from uploaded_blob where id = "+idBlob+" FOR UPDATE ";

                oracle.jdbc.OracleResultSet rs = null;
                oracle.sql.BLOB blob = null;
                try{

                    rs = (oracle.jdbc.OracleResultSet)DBUtil.openResultSet(sql, con);
                    if(rs.next()){
                        blob = rs.getBLOB("file_content");

                        int chunkSize = blob.getChunkSize();
                        byte[] binaryBuffer = new byte[chunkSize];
                        int bytesRead;
                        int position = 1;

                        while ((bytesRead = streamFile.read(binaryBuffer)) != -1) {
                            blob.putBytes(position, binaryBuffer, bytesRead);
                            position += bytesRead;
                        }

                    } else {
                        throw new RuntimeException("Id "+idBlob+" not found");
                    }

                }catch(Exception e){
                    throw new RuntimeException(e);

                }finally{
                    DBUtil.closeResultSet(rs);
                }
            }
            return idBlob;
    }