在 Windows 上使用 Python 連接 MySQL,推薦使用 mysqlclient (MySQLdb 的分支,支援 Python 3)。本文詳細說明預編譯輪子安裝、源碼編譯常見錯誤解決、驗證測試與連線範例。
# 查詢 Python 版本與位元
python -c "import sys; print(sys.version); print('64bit' if sys.maxsize>2**32 else '32bit')"
# 下載對應 .whl (從 https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient)
# 例: mysqlclient-2.1.1-cp39-cp39-win_amd64.whl
pip install mysqlclient-2.1.1-cp39-cp39-win_amd64.whl
或直接 pip install mysqlclient (PyPI 現已提供官方 Windows Wheel)。
>> import MySQLdb
>>> MySQLdb.__version__
'2.1.1'
# 方案 A: 安裝 Visual Studio Build Tools (勾選 C++ 桌面開發)
# 方案 B: 使用 MinGW-w64
pip install mingwpy
# 或設定環境變數 DISTUTILS_USE_SDK=1
修改 site.cfg 或 setup_windows.py 手動指定 MySQL 安裝路徑:
# setup_windows.py
# 註解原註冊表讀取代碼
mysql_root = r"C:\Program Files\MySQL\MySQL Server 8.0"
/Zl 不支援# setup_windows.py
extra_compile_args = [] # 原為 ['/Zl']
# -*- coding: utf-8 -*-
import MySQLdb
conn = MySQLdb.connect(
host="localhost",
user="root",
passwd="password",
db="test_db",
charset="utf8mb4"
)
cursor = conn.cursor()
# 建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS `user` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(50),
`age` INT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# 增
cursor.execute("INSERT INTO user (name, age) VALUES (%s, %s)", ("Tom", 20))
conn.commit()
# 查
cursor.execute("SELECT * FROM user")
for row in cursor.fetchall():
print(row)
# 改
cursor.execute("UPDATE user SET name=%s WHERE id=%s", ("Jerry", 1))
conn.commit()
# 刪
cursor.execute("DELETE FROM user WHERE name=%s", ("Ted",))
conn.commit()
cursor.close()
conn.close()
| 現象 | 原因 | 解決 |
|---|---|---|
ImportError: DLL load failed | 缺少 libmysql.dll 或版本不符 | 確認 MySQL Connector/C 64/32 位元與 Python 一致,或加入 PATH |
| 中文亂碼 | 連線未指定 charset | charset="utf8mb4",資料表亦用 utf8mb4 |
mysqlclient 版本不匹配 _mysql | 殘留舊版編譯檔案 | 刪除 site-packages/MySQLdb _mysql* 重裝 |
PyMySQL:純 Python 實作,無編譯依賴,效能略低但部署極簡 (pip install pymysql)。mysql-connector-python:Oracle 官方驅動,支援 X Protocol。Windows 開發首選 pip install mysqlclient (官方 Wheel),避開編譯地獄。