从Sybase插入/检索文件

时间:2014-08-11 13:17:02

标签: java sybase-ase

我正在尝试将包含的文件插入Sybase数据库。我正在使用JConnect-7.0.7

这是我的表:

CREATE TABLE blob_test (  
blobVar IMAGE  
)

我使用以下方法插入图片:

String sql = "INSERT INTO blob_test VALUES (convert(binary,?))";
PreparedStatement stmt = conn.prepareStatement(sql);
File image = new File(filePath);
InputStream fis = new FileInputStream(image);
int ilen=(int) image.length();
stmt.setBinaryStream(1, fis, ilen);
stmt.execute();

尝试使用以下方法检索图像:

JdbcTemplate jdbcTemplate= new JdbcTemplate(dataSource);
List<Blob> result = jdbcTemplate.query(
         "SELECT blobVar FROM blob_test", new Object[] {}, new RowMapper() {  
                @Override
                public Blob mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return rs.getBlob(1);
                }
            });

for(int i=0;i<result.size();i++){
    Blob b = result.get(i);
    BufferedOutputStream os;

    os = new BufferedOutputStream(new FileOutputStream(new File("output"+i+".zip")));
    os.write(b.getBytes(1, (int) b.length()));
    os.flush();
    os.close();
 }

然而,当我执行我的代码时,它会输出损坏的1kb zip文件。我的代码与oracle数据库完全一样。

或者,我也尝试过这段代码来检索文件:

JdbcTemplate jdbcTemplate= new JdbcTemplate(dataSource);
List<InputStream> result = jdbcTemplate.query(
         "SELECT * FROM blob_test", new Object[] {}, new RowMapper() {
                @Override
                public InputStream mapRow(ResultSet rs, int rowNum) throws SQLException {
                    return lobHandler.getBlobAsBinaryStream(rs, 1);
                }
            });

for(int i=0;i<result.size();i++){
   InputStream in = result.get(i);
   OutputStream out = new FileOutputStream(new File("outputTest"+i+".zip"));
   byte[] buff = new byte[4096];
   int len = 0;

   while ((len = in.read(buff)) != -1) {
       out.write(buff, 0, len);
   }

   out.flush();
   out.close();
}

然而,当我运行此代码时,我得到一个例外:

java.io.IOException: JZ0I9: This InputStream was closed.
    at com.sybase.jdbc4.jdbc.ErrorMessage.raiseIOException(Unknown Source)  at com.sybase.jdbc4.jdbc.ErrorMessage.raiseIOException(Unknown Source)
    at com.sybase.jdbc4.jdbc.RawInputStream.checkMe(Unknown Source)
    at com.sybase.jdbc4.jdbc.RawInputStream.read(Unknown Source)
    at com.sybase.jdbc4.jdbc.RawInputStream.read(Unknown Source)
    at blobtester.BlobTester.getOracleBlob(BlobTester.java:86)
    at blobtester.BlobTester.main(BlobTester.java:34)

同样,这适用于oracle。我缺少哪些与Sybase不同的东西?文件是否正确保存/检索?

修改: 事实证明问题是将文件插入Sybase。我将代码更改为:

File image = new File(filePath); 
InputStream fis = new FileInputStream(image);
LobHandler lobHandler = new DefaultLobHandler();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); 
jdbcTemplate.update("INSERT INTO blob_test VALUES (?)", new Object[] {new SqlLobValue(fis, (int)image.length(), lobHandler)}, new int[] {Types.BLOB});

它适用于Sybase和oracle。感谢。

1 个答案:

答案 0 :(得分:0)

此链接的代码有效:http://forum.spring.io/forum/spring-projects/data/9931-sybase-and-blob-storing

[只需添加答案,即可结束问题。]