JDBC-處理圖片等大的字節數據

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.sql.SQLException;

import com.mysql.jdbc.Clob;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;


public class BlobTest {

	/**
	 * 
	 * 數據庫中讀寫大的字節流
	 * @param args
	 * @throws SQLException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws SQLException, IOException {
		// TODO Auto-generated method stub
//		create();
		read();
	}
	
	static void create() throws SQLException, FileNotFoundException {
		Connection conn = null;
		PreparedStatement ps = null;	
		ResultSet rs = null;
		try {

			conn = JdbcUtil.getConnection();

			String sql = "insert into blob_t values(1 ,?)";
			
			ps = (PreparedStatement) conn.prepareStatement(sql);
			
			File file = new File("src/OK.jpg");
			InputStream input = new BufferedInputStream(new FileInputStream(file));

			ps.setBinaryStream(1, input, (int)file.length());
			
			int count = ps.executeUpdate();

			System.out.println(count + " row affected");
			
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} finally {
			JdbcUtil.free(rs, ps, conn);
		}
	}
	
	static void read() throws SQLException, IOException {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {

			conn = JdbcUtil.getConnection();

			stat = (Statement) conn.createStatement();

			rs = (ResultSet) stat.executeQuery("select blob_bit from blob_t");

			// 處理結果
			while (rs.next()) {
//				Clob clob =  (Clob) rs.getClob("blob_bit");
//				Reader reader  = clob.getCharacterStream();
				InputStream input = rs.getBinaryStream(1);
				File file = new File("OK_mysql.jpg");
				OutputStream output = new BufferedOutputStream(new FileOutputStream(file));
				byte[] buf = new byte[2048];
				int count = 0;
				while((count=input.read(buf)) >0 ){
					output.write(buf, 0, count);
				}
				output.close();
				input.close();
			}
		} finally {
			JdbcUtil.free(rs, stat, conn);
		}
	}

}

注意 ,對應的mysql屬性段的類型爲blob
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章