日期:2014-05-16 浏览次数:20472 次
--Oracle中的Lob类型示例表 create table user_info ( user_id number(10) primary key, name varchar2(20), image blob ); --1. 插入空blob: (如果在数据库中采用默认值方式对Blob字段赋值, 此步可省略) insert into user_info values (1, 'Jacky', empty_blob()); --2. 获得blob的cursor: select image from user_info where user_id = ? for update; --3. 用cursor往数据库写数据: update user_info set image = ? where user_id = ?;
//读取Blob数据 package demo; import java.sql.*; import java.io.*; public class ReadBlob { //加载驱动程序 static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { try { //1. 建立连接 String url = "jdbc:oracle:thin:@localhost:1521:OracleDB"; Connection conn = DriverManager.getConnection(url,"scott","tiger"); conn.setAutoCommit(false); //2. 查询数据 String sql = "select image from user_info where user_id = 1"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); //3. 读取Blob类型数据 Blob blob = null; if(rs.next()) { blob = rs.getBlob(1); } byte[] temp = new byte[(int)blob.length()]; InputStream in = blob.getBinaryStream(); in.read(temp); File file = new File("D:\\img.bmp"); FileOutputStream fout = new FileOutputStream(file); fout.write(temp); in.close(); fout.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
//写Blob数据 package demo; import java.sql.*; import oracle.sql.BLOB;//▲此处的BLOB类全大写, 而java.sql.Blob中的Blob非全大写 import java.io.*; public class WriteBlob { //加载驱动程序 static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { try { //1. 建立与数据库服务器的连接 String url = "jdbc:oracle:thin:@localhost:1521:OracleDB"; Connection conn = DriverManager.getConnection(url,"scott","tiger"); conn.setAutoCommit(false); //2. 首先向表中插入空的Blob //★注意: 对于empty_blob()应放在SQL语句中直接赋值, 使用预置语句的方式赋值无法实现. String sql = "insert into user_info values(?,?,empty_blob())"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, 1); ps.setString(2, "Lucy"); ps.executeUpdate(); //3. 查询Blob, 获得Blob的Cursor sql = "select image from user_info where user_id = ?"; ps = conn.prepareStatement(sql); ps.setInt(1, 1); ResultSet rs = ps.executeQuery(); BLOB blob = null; if(rs.next()) { blob = (BLOB)rs.getBlob(1); } //4. 使用字节流将待入库的文件写入到blob中 File file = new File("D:\\iriver\\sample1.bmp"); FileInputStream fin = new FileInputStream(file); byte[] temp = new byte[fin.available()]; fin.read(temp); OutputStream out = blob.getBinaryOutputStream(); out.write(temp); fin.close(); out.close(); //5. 向数据库中写入数据 sql = "update user_info set image = ? where user_id = ?"; ps = conn.prepareStatement(sql); ps.setBlob(1, blob); ps.setInt(2, 1); ps.executeUpdate(); conn.commit(); } catch (Exception e) { e.printStackTrace(); } } }