JDBC--处理Blob

1、LOB(Large Objects)大对象,是用来存储大量的二进制和文本数据的一种数据类型(一个LOB字段可存储多达4GB的数据)

--LOB分类两种类型:1)内部LOB; 2)外部LOB:

  --内部LOB将数据已字节流的形式存储在数据库的内部。因而,内部LOB的许多操作都可以参与事务,也可以像处理普通数据一样对其进行备份和恢复操作;

    --Oracle支持三种类型的内部LOB:1)BLOB(二进制数据);2)CLOB(单字节字符数据);3)NCLOB(多字节字符数据);

    --CLOB和NCLOB类型适用于存储超长的文本数据,BLOB字段适用于存储大量的二进制数据,如图像、视频、文件等。

  --外部LOB:目前只支持一种外部LOB类型,即BFILE类型,该类型仅存储数据在操作系统中的位置信息,而数据的实体以外部文件的形式存在于文件系统中。

    --BFILE类型所表示的数据都是只读的,不参与事务。该类型可帮助用户管理大量的由外部程序访问的文件。

2、使用JDBC向数据库插入BLOB类型的数据时必须使用PreparedStatement。

3、向Oracle数据库插入Blob类型数据

public void insertBlobData(){
    Connection conn = null;
    PreparedStatement ps = null;
    String sql = "INSERT INTO customers(id, name, picture) VALUES(?,?,?)";
    try{
        conn = JDBCUtils.getConnection();
        ps = conn.prepareStatement(sql);
        ps.setInt(1, 12345);
        ps.setString(2, "Alice");
        
        InputStream in = new FileInputStream("test.jpg");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024]; 
        int len;
        while((len = in.read(b)) != -1){
            baos.write(b, 0, len);
        }
        ps.setBytes(3, baos.toByteArray());
        
        ps.executeUpdate();
        in.close();
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        JDBCUtils.release(conn, ps, null);
    }
}

4、从Oracle数据库中读取Blob类型的数据并通过IO流写入文件中:

public void readBlobData(){
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "SELECT id, name, picture FROM customers WHERE id = ?";
    try{
        conn = JDBCUtils.getConnection();
        ps = conn.prepareStatement(sql);
        ps.setInt(1, 12345);
        rs = ps.executeQuery();
        if(rs.next()){
            Blob blob = rs.getBlob(3);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("out.jpg"));
            InputStream in = blob.getBinaryStream();
            byte[] b = new byte[1024];
            int len;
            while((len = in.read(b)) != -1){
                bos.write(b,0, len);
                bos.flush();
            }
            bos.close();
            in.close();
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        JDBCUtils.release(conn, ps, rs);
    }
}

 

posted on 2015-11-22 13:38  _taoGe  阅读(5557)  评论(0编辑  收藏  举报