CREATE DATABASE IF NOT EXISTS test CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE test;
CREATE TABLE IF NOT EXISTS Images (
Id INT PRIMARY KEY AUTO_INCREMENT,
Data MEDIUMBLOB NOT NULL COMMENT '圖片二進制資料,最大 16MB',
FileName VARCHAR(255) NOT NULL,
ContentType VARCHAR(100) NOT NULL,
FileSize INT UNSIGNED NOT NULL,
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
BLOB 型別選擇:TINYBLOB(255B) /BLOB(64KB) /MEDIUMBLOB(16MB) /LONGBLOB(4GB)。圖片建議MEDIUMBLOB或LONGBLOB。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
將圖片讀為二進制寫入 MySQL BLOB 欄位
依賴:pip install mysqlclient (或 PyMySQL)
"""
import sys
import mysql.connector # 或 import pymysql as mysql
# ===== 設定區 =====
DB_CONFIG = {
'host': 'localhost',
'user': 'root',
'password': 'root',
'database': 'test',
'charset': 'utf8mb4',
'autocommit': False
}
IMAGE_PATH = '../web.jpg' # 相對路徑,請依實際調整
# ===================
def read_image_as_binary(path: str) -> bytes:
"""以二進位模式讀取圖片"""
try:
with open(path, 'rb') as f:
return f.read()
except IOError as e:
print(f"[ERROR] 讀取圖片失敗:{e}", file=sys.stderr)
sys.exit(1)
def insert_image(conn, img_data: bytes, filename: str, content_type: str):
"""寫入資料庫,使用參數化查詢防 SQL Injection"""
sql = """
INSERT INTO Images (Data, FileName, ContentType, FileSize)
VALUES (%s, %s, %s, %s)
"""
cursor = conn.cursor()
try:
cursor.execute(sql, (img_data, filename, content_type, len(img_data)))
conn.commit()
print(f"[OK] 圖片已寫入,Id={cursor.lastrowid},大小={len(img_data)} bytes")
except mysql.connector.Error as e:
conn.rollback()
print(f"[ERROR] 寫入失敗:{e}", file=sys.stderr)
raise
finally:
cursor.close()
def main():
img_bytes = read_image_as_binary(IMAGE_PATH)
# 偵測 MIME 類型(簡易版)
import mimetypes
mime_type, _ = mimetypes.guess_type(IMAGE_PATH)
if mime_type is None:
mime_type = 'application/octet-stream'
try:
conn = mysql.connector.connect(**DB_CONFIG)
insert_image(conn, img_bytes, IMAGE_PATH, mime_type)
except mysql.connector.Error as e:
print(f"[ERROR] 資料庫連線失敗:{e}", file=sys.stderr)
sys.exit(1)
finally:
if 'conn' in locals() and conn.is_connected():
conn.close()
if __name__ == '__main__':
main()
open(path, 'rb'),Python 3 bytes 直接對應 MySQL BLOB,無需手動編碼/轉義。cursor.execute(sql, (img_data, ...)),驅動程式自動處理二進位轉義,**嚴禁**字串格式化 ... VALUES ('{img_data}')。autocommit=False,成功 commit()、失敗 rollback()。LONGBLOB + MySQLdb.escape_string 分批寫入或改用 LOAD_FILE()(需檔案在伺服器端)。def save_image_from_db(conn, image_id: int, output_path: str):
cursor = conn.cursor()
cursor.execute("SELECT Data, FileName FROM Images WHERE Id = %s", (image_id,))
row = cursor.fetchone()
cursor.close()
if row:
with open(output_path, 'wb') as f:
f.write(row[0])
print(f"[OK] 圖片已還原至 {output_path}")
else:
print("[WARN] 找不到指定圖片")
| 場景 | 建議 |
|---|---|
| 縮圖/小圖 (< 1MB) | 直接存 BLOB,簡單可靠 |
| 大圖/原圖 (> 1MB) | 存檔案系統/MinIO/S3,DB 存路徑 + 雜湊值 |
| 高併發讀取 | 加 CDN/反向代理快取,DB 僅存元資料 |
| 備份策略 | 資料庫備份含 BLOB 會極大,建議分離備份或增量備份 |
Python 3 + mysqlclient/PyMySQL 存取 MySQL BLOB 極為直觀:**二進位讀檔 → 參數化寫入 → 交易提交**。牢記「大檔不存 DB、參數化防注入、交易保一致性」三大鐵律,即可安心管理二進位資料。