數據庫準備
CREATE TABLE Images (
Id INT PRIMARY KEY AUTO_INCREMENT,
Data MEDIUMBLOB -- 支持最大 16MB,大文件用 LONGBLOB
);
Python 存圖代碼
# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
try:
# 1. 讀取圖片二進制數據
with open("../web.jpg", "rb") as f: # 必須用 'rb' 二進制模式
img_data = f.read()
except IOError as e:
print(f"Error {e.args[0]}: {e.args[1]}")
sys.exit(1)
try:
# 2. 連接數據庫
conn = mdb.connect(host='localhost', user='root', passwd='root', db='test')
cursor = conn.cursor()
# 3. 參數化插入(防 SQL 注入,自動處理轉義)
cursor.execute("INSERT INTO Images (Data) VALUES (%s)", (img_data,))
# 4. 提交事務
conn.commit()
print("圖片存入成功")
except mdb.Error as e:
print(f"Error {e.args[0]}: {e.args[1]}")
conn.rollback()
finally:
cursor.close()
conn.close()
關鍵點提示
| 要點 | 說明 |
| 二進制讀取 | open(..., "rb") 必須指定 b 模式 |
| 參數化查詢 | execute(sql, (params,)) 元組傳參,驅動自動轉義 |
| BLOB 類型選擇 | TINYBLOB(255B) / BLOB(64KB) / MEDIUMBLOB(16MB) / LONGBLOB(4GB) |
| 大文件分塊 | 超大文件建議分塊寫入或存文件系統、數據庫存路徑 |
| 讀取還原 | cursor.execute("SELECT Data FROM Images WHERE Id=1") → data = cursor.fetchone()[0] → open('out.jpg','wb').write(data) |
現代替代:使用 mysqlclient 或 PyMySQL
# PyMySQL 示例
import pymysql
conn = pymysql.connect(host='localhost', user='root', password='root', db='test')
with conn.cursor() as cur:
cur.execute("INSERT INTO Images (Data) VALUES (%s)", (img_data,))
conn.commit()