자바 my sql 큰 파일 읽 기 자바. sql. blob

2313 단어
package day18;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.ResultSet;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import day17.DBManager;

public class TestBlob {

	public static void main(String[] args) throws Exception {
		TestBlob t=new TestBlob();
		//t.savePic();
		t.readPic();
	}
    public void readPic() throws Exception{//   
    	DBManager dbManager=null;
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		dbManager=new DBManager();
		//    
		conn=dbManager.getConnection();
		String sql="select * from pic where id=?";
//		FileInputStream fis=new FileInputStream(
//				new File("D:\\workspace\\WebDatabase\\src\\day18\\Penguins.jpg"));
		pstmt=(PreparedStatement) conn.prepareStatement(sql);
		pstmt.setInt(1,3);
	     Blob blob=null;
		rs=pstmt.executeQuery();
		if(rs.next()){
			blob=rs.getBlob(1);
		}
		//       
		FileOutputStream fos=
			new FileOutputStream("D:\\workspace\\WebDatabase\\src\\day18\\xxx.png");
		//       
		BufferedOutputStream bos=new BufferedOutputStream(fos);
		if(blob!=null){
			//          
			InputStream ins=blob.getBinaryStream();
			BufferedInputStream bis=new BufferedInputStream(ins);
			
			//               
			int len=0;
			byte[] b=new byte[1024];
			while((len=bis.read(b))!=-1){
				//      
				bos.write(b,0,len);
			}
			bos.close();
			bis.close();
			
		}	
		//    
		dbManager.closeResource(conn,pstmt,rs);
    }
    public void savePic() throws Exception{
    	DBManager dbManager=null;
		Connection conn=null;
		PreparedStatement pstmt=null;
		dbManager=new DBManager();
		//    
		conn=dbManager.getConnection();
		String sql="insert into pic(id,pic) values(?,?)";
		FileInputStream fis=new FileInputStream(
				new File("D:\\workspace\\WebDatabase\\src\\day18\\1.png"));
		pstmt=(PreparedStatement) conn.prepareStatement(sql);
		pstmt.setInt(1,3);
		pstmt.setBlob(2, fis);
		int k=pstmt.executeUpdate();
		System.out.println("k== "+k);
		//    
		dbManager.closeResource(conn,pstmt,null);
    }
}

DB Manager. 자바

좋은 웹페이지 즐겨찾기