未遇到问题,先记录,防止以后找不到资源
package com.you.sister; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; public class BlobTest { public static Connection conn; public static Connection getConn() throws Exception { FileInputStream fis = new FileInputStream(new File("jdbc.properties")); Properties prop = new Properties(); prop.load(fis); String driver = prop.getProperty("jdbc.driver"); String url = prop.getProperty("jdbc.url"); String username = prop.getProperty("jdbc.username"); String password = prop.getProperty("jdbc.password"); Class.forName(driver); return DriverManager.getConnection(url, username, password); } public static void main(String[] args) throws Exception { conn = getConn(); readBlob(); writeBlob(); conn.close(); } /** * 从数据库中读大对象出来 * 保存在本地 */ public static void readBlob() { try { String readSql = "select * from emp where empno = ?"; PreparedStatement ps = conn.prepareStatement(readSql); ps.setInt(1, 7369); ResultSet rs = ps.executeQuery(); while (rs.next()) { Blob image = rs.getBlob("image"); DataOutputStream dos = // 在FileOutputStream中指定文件输出路径 new DataOutputStream(new FileOutputStream(7369 + "_image.jpeg")); InputStream fis = image.getBinaryStream(); int out; byte[] outByte = new byte [100]; // 将blob对象输入流写入本地输出流中 while ((out = fis.read(outByte)) != -1) { dos.write(outByte); } fis.close(); dos.flush(); dos.close(); } rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 将大对象文件保存进数据库中 */ public static void writeBlob() { try { BufferedInputStream fis = new BufferedInputStream(new FileInputStream(new File("D:\\Tulips.jpg"))); // 如果是新插入字段,则将大对象对应字段插入为empty_clob(); // 如果是修改,则可以先update 该行数据,将大对象对应字段设置为empty_clob(); String writeSql = "select * from emp where empno = ? for update"; PreparedStatement ps = conn.prepareStatement(writeSql); ps.setInt(1, 7499); conn.setAutoCommit(false); ResultSet rs = ps.executeQuery(); while (rs.next()) { oracle.sql.BLOB image = (oracle.sql.BLOB)rs.getBlob("image"); BufferedOutputStream bos = new BufferedOutputStream(image.getBinaryOutputStream()); int c; // 将实际文件中的内容以二进制的形式来输出到blob对象对应的输出流中 while ((c = fis.read()) != -1) { bos.write(c); } fis.close(); bos.close(); } conn.commit(); rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } } }
从数据库中读blob对象出来相对比较容易
从本地向数据库写blob对象相对难一些,主要注意两点:
1 要处理的blob字段必须先设置为empt_clob()
2 使用事务控制向数据库的写入操作