欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-20 15:29:28
...
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");
	}
}
相关标签: Blob java