Java 对Oracle数据库中的 BLOB类型 插入图片

package test;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test {
	private Connection conn;

	/**
	 * 得到一个数据库的连接
	 * 
	 * @return 返加Connection对象
	 */
	public Connection getConnection() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:lyx", "scott", "tiger");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 向表中插入图片
	 * 
	 * @param path图片所在的路径
	 * @return 整形 判断成功或失败
	 */
	public int insertImage(String path) throws Exception {
		int i = 0;
		Statement st = null;
		ResultSet rs = null;
		conn=this.getConnection();
		
		conn.setAutoCommit(false);//设置数据库为不自动提交,必须的一步
		st = conn.createStatement();
		//先插入一个空对象,这里我调用了Empty_BLOB()函数
		i = st
				.executeUpdate("insert into image (id,image) values (seq1.nextval,Empty_BLOB())");
		//以行的方式锁定
		rs = st
				.executeQuery("select image from image where id=(select max(id) from image) for update");
		if (rs.next()) {
			//得到流
			oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
			//从得到的低级流构造一个高级流
			PrintStream ps = new PrintStream(blob.getBinaryOutputStream());
			BufferedInputStream bis = new BufferedInputStream(
					new FileInputStream(path));
			byte[] buff = new byte[1024];
			int n = 0;
			//从输入到输出
			while ((n = bis.read(buff)) != -1) {
				ps.write(buff, 0, n);

			}
			//清空流的缓存
			ps.flush();
			//关闭流,注意一定要关
			ps.close();
			bis.close();
		}
		rs.close();
		st.close();
		conn.close();
		return i;
	}

	public static void main(String[] args) throws Exception {
		Test test=new Test();
		test.insertImage("e:\\3.jpg");
		System.out.println("OK");


	}

}

 

转载于:https://my.oschina.net/u/2299924/blog/2250533

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值