Linux 下 pip install mysqlclient 一條龍,Windows 因編譯依賴常遇阻。本文針對 Win7 64 位 + Python 2.7 環境,記錄兩大核心報錯完美解決。
MySQL-python-1.2.3(即 MySQLdb)運行 MySQL-python-1.2.3.win-amd64-py2.7.exe 安裝程序彈窗報錯。
Python 安裝時選擇「所有用戶」會將註冊表寫入 HKEY_LOCAL_MACHINE;選擇「當前用戶」寫入 HKEY_CURRENT_USER。安裝程序只搜尋 HKLM,找不到即報錯。
# register.py
import sys
from _winreg import *
version = sys.version[:3]
installpath = sys.prefix
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % version
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (installpath, installpath, installpath)
def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
print "--- Python", version, "is now registered!"
return
except:
print "*** Unable to register!"
return
if QueryValue(reg, installkey) == installpath and QueryValue(reg, pythonkey) == pythonpath:
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register! You probably have another Python installation!"
if __name__ == "__main__":
RegisterPy()
python register.py
輸出 --- Python 2.7 is now registered! 即成功,再次運行安裝程序即可通過。
ImportError: DLL load failed: %1 不是有效的 Win32 應用程序
Python 位數與 MySQLdb 位數不匹配。常見:Python 32 位 + MySQLdb 64 位(win-amd64)。
python -c "import struct; print(struct.calcsize('P') * 8)"MySQL-python-1.2.3.win32-py2.7.exeMySQL-python-1.2.3.win-amd64-py2.7.exeMySQL-python 專案已停止維護(最後更新 2014),純 Python 實現 PyMySQL 或 C 擴展 mysqlclient 是現代選擇:
# 純 Python,跨平台無編譯依賴
pip install PyMySQL
# mysqlclient 是 MySQL-python 分支,修復眾多 Bug,支援 Python 3
pip install mysqlclient # Windows 需預裝 Visual C++ Build Tools
# PyMySQL 兼容 MySQLdb API
import pymysql
pymysql.install_as_MySQLdb() # 後續代碼可直接 import MySQLdb
import MySQLdb
conn = MySQLdb.connect(host='localhost', user='root', passwd='***', db='test')
PyMySQL/mysqlclient 避免編譯地獄