java操作oracle数据库中的blob字段

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(); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值