oracle中的BLOB字段是存储2进制的文件,比如文件,图片等。
1、把本地文件写入数据库
package com.data; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; public class WriteBlob { /** * beckham 2009-12-7 下午09:47:36 */ public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); String url = "jdbc:oracle:thin:@localhost:1521:menhu"; String user = "zm"; String password = "zm"; Connection conn = DriverManager.getConnection(url, user, password); // 设置手动提交 conn.setAutoCommit(false); Statement sta = null; ResultSet rs = null; PreparedStatement ps = null; // 插入空值 String sql = "insert into mytest values(3,empty_blob()) "; sta = conn.createStatement(); sta.executeUpdate(sql); conn.commit(); // 锁定并编辑当前数据 sql = "select images from mytest where id=3 for update"; rs = sta.executeQuery(sql); if (rs.next()) { oracle.sql.BLOB b = (oracle.sql.BLOB) rs.getBlob("images"); // 输入流 OutputStream os = b.getBinaryOutputStream(); // 输出流 FileInputStream fiis = new FileInputStream(new File("1.doc")); // 入库 byte[] tmp = new byte[1024]; int a = 0; while ((a = fiis.read(tmp)) != -1) { os.write(tmp, 0, a); os.flush(); } os.close(); fiis.close(); } conn.commit(); rs.close(); sta.close(); conn.close(); } }
2、从数据库中读取Blob字段数据
package com.data; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ReadBlob { /** * beckham 2009-12-8 下午03:49:30 */ public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); String url = "jdbc:oracle:thin:@localhost:1521:menhu"; String user = "zm"; String password = "zm"; Connection conn = DriverManager.getConnection(url, user, password); conn.setAutoCommit(false); String sql = "select images from mytest where id=3"; Statement sta = null; ResultSet rs = null; sta = conn.createStatement(); rs = sta.executeQuery(sql); while (rs.next()) { //数据库-->本地文件 oracle.sql.BLOB b = (oracle.sql.BLOB) rs.getBlob("images"); InputStream fis = b.getBinaryStream() ; FileOutputStream fos = new FileOutputStream(new File("D://1.doc")); byte[] tmp = new byte[1024]; int a = 0; while ((a = fis.read(tmp)) != -1) { fos.write(tmp,0,a); fos.flush() ; } fos.close(); fis.close(); } conn.commit(); rs.close(); sta.close(); conn.close(); } }