首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python3 圖片轉二進制存入 MySQL BLOB 字段完整代碼

     編輯:更多程式設計知識

數據庫準備

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()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved