JDBC中級篇(MYSQL)——處理文件(BLOB)

微笑注意:其中的JdbcUtil是我自定義的鏈接工具類:代碼例子連接:java

package b_blob_clob;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import util.JdbcUtil;
/**
 * 關於BLOB:文件
 * 
 * @author mzy
 *
 */
public class Demo02 {
	public static void main(String[] args) {
		// write();
		
		/**
		 * 讀取
		 */
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try{
			conn = JdbcUtil.getConnection();
			String sql = "select * from news where id=?";
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, 1);
			rs = stmt.executeQuery();
			
			while(rs.next()){
			
				//讀取blob字段
				Blob blob = rs.getBlob("attachments");
				//經過blob字段獲取輸入字節流
				InputStream in = blob.getBinaryStream();
				
				//把輸入字節流寫出文件中
				FileOutputStream out = new FileOutputStream("e:/srceen.exe");
				byte[] buf = new byte[1024];
				int len = 0;
				//邊讀邊寫
				while( (len=in.read(buf))!=-1  ){
					out.write(buf, 0, len);
				}  
				//關閉流
				out.close();
				in.close();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtil.close(stmt, conn);
		}
	}

	private static void write() {
		/**
		 * 寫入
		 */
		Connection conn = null;
		PreparedStatement stmt = null;
		try{
			conn = JdbcUtil.getConnection();
			String sql = "update news set attachments=? where id=?";
			//預編譯
			stmt = conn.prepareStatement(sql);
			//參數賦值
			/**
			 * 讀取本地字節文件
			 * 注意:
			 * 	1)發送的數據內容超過了字段的長度限制,則拋出 Data too long...異常,這時須要修改字段的類型
			 *  2)發送的數據內容超過了1MB(mysql服務器默認的接收數據包的大小),能夠到mysql安裝目錄下的my.ini文件添加一個變量max_allowed_packet=50M便可!
			 */
			// InputStream in = new FileInputStream("./src/4.jpg"); // 圖片大小小於65KB的時候
			// Data too long for column 'attachments'
			// InputStream in = new FileInputStream("./src/6.jpg"); // 圖片大小大於65KB
			// 修改attachments:字段的類型從BLOB到mediumBLOB:限制大小爲16MB,再大就只能使用LongBLOB了 4GB
			// InputStream in = new FileInputStream("./src/6.jpg"); // 成功
			
			// 上傳大小大於1MB的
			InputStream in = new FileInputStream("./src/InletexEMC.exe");
			// 這裏直接添加成功,若是沒有成功須要去mysql的my.ini中配置
			// max_allowed_packet=隨意大小
			/**
			 * 設置blob字段
			 */
			stmt.setBlob(1, in);
			stmt.setInt(2, 1);
			//執行
			stmt.executeUpdate();
			System.out.println("添加成功");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JdbcUtil.close(stmt, conn);
		}
	}
}
相關文章
相關標籤/搜索