Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

MySQL 用 BLOB 欄位存圖片:完整操作示例

把圖片存進資料庫,是初學者常想試、卻又常踩坑的題目。做法本身不難:在 MySQL 建一個 BLOB 系列欄位,寫入時用 setBinaryStream() 把檔案串流塞進去,讀取時用 getBinaryStream() 或 getBytes() 取出位元組,再交給 ImageIcon 還原成圖像。

表結構

create table view (
    id      int unsigned NOT NULL AUTO_INCREMENT,
    catid   int,
    title   varchar(256),
    picture MEDIUMBLOB,
    content TEXT,
    PRIMARY KEY (id)
);

這裡選 MEDIUMBLOB(約 16MB 上限)而非 BLOB(64KB),因為 BLOB 存照片很快就會爆。

讀取:把串流拼回位元組

public static View getView(Integer catId) {
    View view = new View();
    try {
        String sql = "SELECT title, content, picture FROM view where catid=? limit 1";
        PreparedStatement stmt = BaseDaoFactory.getInstance().prepareStatement(sql);
        stmt.setInt(1, catId);
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            view.setTitle(rs.getString(1));
            view.setContent(rs.getString(2));

            ByteBuffer bb = ByteBuffer.allocate(1024 * 1024);
            byte[] buffer = new byte[1];
            InputStream is = rs.getBinaryStream(3);
            while (is != null && is.read(buffer) > 0) {
                bb.put(buffer);
            }
            view.setImage(new ImageIcon(bb.array()).getImage());
        }
        return view;
    } catch (IOException | SQLException ex) {
        Logger.getLogger(ViewPointDao.class.getName())
              .log(Level.SEVERE, null, ex);
    }
    return null;
}

這裡刻意用 1 位元組的緩衝區逐筆讀,是為了示範串流的「一次一點、慢慢填」本質;實務上請改成 4KB~8KB 的緩衝區,差異會非常明顯。另外 ByteBuffer.allocate(1MB) 是寫死容量,圖片一大就會 BufferOverflowException,正式版本建議改用 ByteArrayOutputStream 動態累積。

新增:檔案串流直接入庫

public static boolean addView(View view) {
    FileInputStream fis = null;
    try {
        if (exit(view.getCatId())) {       // 已存在則走更新
            return update(view);
        }
        String sql = "INSERT INTO view (title, content, catid, picture) VALUES (?, ?, ?, ?)";
        PreparedStatement stmt = BaseDaoFactory.getInstance().prepareStatement(sql);
        stmt.setString(1, view.getTitle());
        stmt.setString(2, view.getContent());
        stmt.setInt(3, view.getCatId());

        if (view.getImageFile() != null) {
            File image = new File(view.getImageFile());
            fis = new FileInputStream(image);
            // image.length() 回傳檔案大小,作為串流長度
            stmt.setBinaryStream(4, fis, (int) image.length());
        } else {
            stmt.setBinaryStream(4, null, 0);
        }
        return stmt.executeUpdate() > 0;
    } catch (IOException | SQLException ex) {
        Logger.getLogger(ViewPointDao.class.getName())
              .log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (fis != null) fis.close();
        } catch (IOException ex) { /* 忽略關流錯誤 */ }
    }
    return false;
}

setBinaryStream() 的第三個參數是串流長度,用 image.length() 取得;沒有圖片時傳 null, 0。更新(update)的邏輯相同,只是把 SQL 換成 update view set title=?, content=?, picture=? where catid=?,並依「有沒有換圖」動態決定要不要帶上 picture 欄位。另外先用 exit(catId) 查一次是否存在,再決定新增或更新,是這個範例的取捨;並行環境下更穩妥的做法是交由資料庫的 ON DUPLICATE KEY UPDATE 處理。

承接用的 Bean

public class View {
    private String title;      // 標題
    private String content;    // 內容
    private Image  image;      // 圖片物件
    private String imageFile;  // 圖片上傳路徑
    private int    catId;      // 分類 id
    // getter / setter 略
}

該不該這樣做

把圖片塞進資料庫,優點是資料一致性好、備份還原單純,不必擔心「檔在庫不在」;缺點是資料庫膨脹快、查詢列表時容易誤帶大欄位、備份檔案也會肥大。多數線上系統仍選擇「圖存檔案系統或物件儲存,庫裡只留路徑」。若確定要走 BLOB 路線,記得三件事:查詢時明確列出需要的欄位、寫入用 PreparedStatement 避免拼接 SQL、串流與連線務必在 finally 或 try-with-resources 中關閉。

Copyright © Linux教程網 All Rights Reserved