萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

macOS MAMP 環境安裝 MySQL-Python 報錯「mysql_config not found」與「my_config.h not found」完美解決

問題場景

macOS + MAMP 集成環境,pip install MySQL-python 失敗:

  1. EnvironmentError: mysql_config not found
  2. 修復後 fatal error: 'my_config.h' file not found

根因分析

  • MAMP 將 MySQL 安裝在 /Applications/MAMP/Library,非系統默認路徑
  • mysql_config 腳本路徑不在 PATH,setup.py 找不到
  • MAMP 自帶 MySQL **缺少開發頭文件**(my_config.h 等),無法編譯 C 擴展

分步解決方案

步驟 1:修正 mysql_config 路徑

# 1. 下載源碼包(非 wheel)
pip download MySQL-python --no-binary :all:
tar xzf MySQL-python-*.tar.gz
cd MySQL-python-*

# 2. 編輯 setup_posix.py
vim setup_posix.py
# 找到 mysql_config 路徑定義處,修改為 MAMP 實際路徑:
# mysql_config.path = "/Applications/MAMP/Library/bin/mysql_config"

# 3. 源碼安裝
python setup.py install

步驟 2:補全開發頭文件

# 使用 Homebrew 安裝 MySQL Connector C(包含頭文件/庫)
brew install mysql-connector-c

# 驗證頭文件存在
ls /usr/local/include/mysql*/my_config.h

步驟 3:重新安裝 MySQL-python

cd MySQL-python-*
python setup.py install

現代替代方案(強烈推薦)

MySQL-python(即 MySQLdb)已停止維護,**建議遷移至純 Python 實現的驅動**:

Django 遷移示例

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'DRIVER': 'pymysql',  # 或不寫,mysqlclient 自動檢測
        ...
    }
}

# 項目入口 __init__.py(僅 PyMySQL 需要)
import pymysql
pymysql.install_as_MySQLdb()

避坑總結

  • **不要在虛擬環境外安裝系統級包**
  • **優先選擇 wheel 包**(pip install mysqlclient 通常直接下載預編譯 wheel,無需編譯)
  • MAMP 僅適合本地開發調試,**生產環境請使用標準 MySQL 安裝包或容器**
copyright © 萬盛學電腦網 all rights reserved
驅動安裝命令特點
PyMySQLpip install PyMySQL純 Python、無 C 擴展、兼容 MySQLdb API、Django 官方推薦
mysqlclientpip install mysqlclientMySQLdb 分支、C 加速、積極維護、生產首選