且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:从Oracle读取Blob

更新时间:2023-02-14 19:17:32

您可以通过以下方式获取InputStream对象 ResultSet.getBinaryStream()方法。

You may obtain InputStream object via ResultSet.getBinaryStream() method.

PreparedStatement prepareStatement = con.prepareStatement("select * from SMD_DATESTREEMAP");
ResultSet rs=prepareStatement.executeQuery();

while(rs.next())
      {
       oracle.jdbc.driver.OracleBlobInputStream bos=(oracle.jdbc.driver.OracleBlobInputStream) rs.getBinaryStream(2) ;

       ObjectInputStream out = new ObjectInputStream(bos);

       map=(TreeMap<DateTime, Integer>)out.readObject();
       ...
      }

您可以编写字节数组而不是二进制流。

You may write byte array instead of binary stream.

      ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
      ObjectOutputStream out = new ObjectOutputStream(bos);
      out.writeObject(map);
      out.flush();
      out.close();
      byte[] buf = bos.toByteArray();

      PreparedStatement prepareStatement = con.prepareStatement("INSERT INTO SMD_DATESTREEMAP VALUES(?,?)");
      prepareStatement.setInt(1, 1);
      prepareStatement.setBytes(2, buf);
      prepareStatement.executeUpdate();
      prepareStatement.close();

并读取字节数组:

     while(rs.next())
      { 
       byte []buf=rs.getBytes(2);
       ByteArrayInputStream bos=new ByteArrayInputStream(buf);
       ObjectInputStream out = new ObjectInputStream(bos);
       map=(TreeMap<DateTime, Integer>)out.readObject();
       ..
       }