1. 程式人生 > >oracle資料庫儲存圖片

oracle資料庫儲存圖片

drop table mytest;
create table mytest(
		  id varchar2(4) not null primary key,
		  pc BLOB 
		);
commit;

儲存圖片要將圖片轉換成二進位制儲存

首先在oracle中建一張表,如上圖所示,id代表索引,pc用來儲存圖片的二進位制碼。

下面的java程式碼就是進行圖片的儲存和取出;url,user.password就是你自己資料庫的ip,使用者名稱和密碼

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class Picture {


	public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
		//資料庫連線
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url = "";
		String user= "system";
		String password = "123456";
		Connection conn = DriverManager.getConnection(url,user, password);
		
		//讀取本地圖片
		File file1 = new File("C:\\Users\\pc\\Desktop\\src.jpg");
		//得到大小
		int length = (int) file1.length();
		//獲得檔案輸入流
		InputStream input = new FileInputStream(file1);
		
		//資料庫插入圖片
		String sql = "INSERT   INTO   mytest   (id,pc)   VALUES(?,?)";
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1, "1");
		stmt.setBinaryStream(2,input,length);
		stmt.execute();
		
		
		//從資料庫中讀取圖片
		
		//存放資料庫中的圖片
		File file2 = new File("C:\\Users\\pc\\Desktop\\dec.jpg");
		//從資料庫中查詢圖片
		PreparedStatement stmt1 = conn.prepareStatement("select * from mytest where id = ?");
		stmt1.setObject(1, 1);
		//得到結果
		ResultSet rs = stmt1.executeQuery();
		if (rs.next()) {
			OutputStream fos = new FileOutputStream(file2);
            InputStream is = rs.getBinaryStream("pc");
            byte[] buffer = new byte[4 * 1024];
            int length1 = 0;
            while ((length1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, length1);
		}
            fos.flush();
            fos.close();
            is.close();
	}
}
}