日期:2014-05-16 浏览次数:20483 次
create table blogtest(id number primary key,name varchar2(20),picture blob);
package August; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class OracleBlobTest { public static void main(String[] args) { } public static void readBlob() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@127.0.0.1:1521/july", "scott", "snaillocke"); Statement st = conn.createStatement(); PreparedStatement ps = conn.prepareStatement("select * from BLOBTEST where id = ?"); ps.setInt(1, 1); ResultSet rs = ps.executeQuery(); rs.next(); oracle.sql.BLOB imgBlob = (oracle.sql.BLOB) rs.getBlob(3); // 将二进制数据写入BLOB try{ FileOutputStream outStream = new FileOutputStream("D:/oracleback.png"); InputStream inStream = imgBlob.getBinaryStream(); byte[] buf = new byte[10240]; int len; while ((len = inStream.read(buf)) > 0) { outStream.write(buf, 0, len); } inStream.close(); outStream.close(); }catch(Exception e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static void writeBlob() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@127.0.0.1:1521/july", "scott", "snaillocke"); Statement st = conn.createStatement(); // 插入一个空对象empty_blob() // 锁定数据行进行更新,注意“for update”语句 PreparedStatement ps = conn.prepareStatement("insert into BLOBTEST (ID, NAME, PICTURE) values (1,'fang.jpg',?)"); // 通过ORALCE.SQL.BLOB/CLOB.EMPTY_LOB()构造空BLOB/CLOB对象 ps.setBlob(1, oracle.sql.BLOB.empty_lob()); ps.execute(); ps.close(); // 再次对读出BLOB/CLOB句柄 ps = conn .prepareStatement("SELECT * FROM BLOBTEST WHERE ID=? FOR UPDATE"); ps.setInt(1, 1); ResultSet rs = ps.executeQuery(); rs.next(); oracle.sql.BLOB imgBlob = (oracle.sql.BLOB) rs.getBlob(3); // 将二进制数据写入BLOB try{ FileInputStream inStream = new FileInputStream("D:/My Pictures/oracle.png"); OutputStream outStream = imgBlob.getBinaryOutputStream(); byte[] buf = new byte[10240]; int len; while ((len = inStream.read(buf)) > 0) { outStream.write(buf, 0, len); } inStream.close(); outStream.close(); }catch(Exception e) { e.printStackTrace(); } // 再将Blob字段更新到数据库 ps = conn .prepareStatement(" update BLOBTEST set PICTURE=?"); ps.setBlob(1, imgBlob); ps.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }