首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

Oracle中blob门类的读取

2012-08-03 
Oracle中blob类型的读取虽然用blob的情况不多,但是还是得了解一下,网上看得有点乱,而且没有看到从数据读bl

Oracle中blob类型的读取
虽然用blob的情况不多,但是还是得了解一下,网上看得有点乱,而且没有看到从数据读blob的。在此总结一下:
数据库中的建表语句如下:

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);// 将二进制数据写入BLOBtry{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);// 将二进制数据写入BLOBtry{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();}}}

以上代码必须导入Oracle驱动包

热点排行