用JDBC中的Blob向oracle中插入和读取图片信息

import java.io.*;
import java.sql.*;

public class  Test{

	public static Connection con = null;
	public static String driver = "oracle.jdbc.driver.OracleDriver";
	public static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
	public static String user = "scott";
	public static String password = "trigger";

	static {
		try{
			Class.forName(driver);
			con = DriverManager.getConnection(url,user,password);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

//  插入图片
	public static void insertImage(String path){
		String sql = "insert into images(id,image) values(?,?)";
		try{
			File file = new File(path);
			BufferedInputStream buffer = new BufferedInputStream(new FileInputStream(file));
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1,"1234");
			pstmt.setBinaryStream(2,buffer);
			pstmt.execute();
			pstmt.close();
			buffer.close();

		}catch(Exception e){
			e.printStackTrace();
		}

	}

//  获取图片
	public static void getImage(String path){
		String sql = "select * from images where id=?";
		Blob blob = null;
		try{
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1,"1234");
			ResultSet rs = pstmt.executeQuery();
			if(rs.next()){
				blob = rs.getBlob("image");
			}

			byte []buf = new byte[4096];
			int c = 0;
			File file = new File(path);
			FileOutputStream fo = new FileOutputStream(file);
			BufferedInputStream buffer = new BufferedInputStream(blob.getBinaryStream());
//			InputStream buffer = blob.getBinaryStream();
			while((c=buffer.read(buf))!=-1){
				fo.write(buf);
			}
			buffer.close();
			fo.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void main(String []args){
		insertImage("./aaa.jpg");
		getImage("./bbb.jpg");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值