处理BLOB
oracle LOB
LOB(Large Objects大对象),用来存储大量的二进制和文本数据的一种数据类型
内部LOB
BLOB(二进制数据)
CLOB(单字节字母数据)
NCLOB(多字节字符数据)
外部LOB
插入BLOB类型的数据必须使用PreparedStatement。
因为BLOB类型的数据时无法使用字符串拼写的。
调用setBlob(int index,InputStream inputStream)
@Test public void test4(){ Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "insert into student values(?,?,?,?)"; try { conn = Methods.getConnection(); preparedStatement = conn.prepareStatement(sql); preparedStatement.setObject(1,"5"); preparedStatement.setString(2,"yang5"); preparedStatement.setString(3,"1235"); InputStream inputStream = new FileInputStream("boy.png"); preparedStatement.setBlob(4,inputStream); preparedStatement.executeUpdate(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { Methods.release(preparedStatement,conn,resultSet); } }
读取blob数据:
1.使用getBlob方法读取Blob对象
2.调用Blob的getBinaryStream()方法得到输入流,在使用IO操作即可。
@Test public void test5(){ Connection conn = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String sql = "select picture from student where id =5"; try { conn = Methods.getConnection(); preparedStatement = conn.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); if(resultSet.next()){ Blob picture = resultSet.getBlob(1); InputStream in = picture.getBinaryStream(); OutputStream os = new FileOutputStream("boy1.png"); byte[] buffer = new byte[1024]; int len = 0; while((len= in.read(buffer))!=-1){ os.write(buffer,0,len); } os.close(); in.close(); } } catch (Exception e) { e.printStackTrace(); } finally { Methods.release(preparedStatement,conn,resultSet); } }