sudo apt install mysql-server (Ubuntu/Debian) 或 sudo yum install mysql-server (CentOS/RHEL)。推薦 **mysqlclient**(C 封裝、效能最佳、支援 Python 3.7+):
pip install mysqlclient
替代選擇:
PyMySQL:純 Python 實作、無需編譯、相容性佳 pip install PyMySQL。mysql-connector-python:Oracle 官方驅動。import MySQLdb
conn = MySQLdb.connect(
host='localhost', # 資料庫主機
port=3306, # 埠號,預設 3306
user='root', # 登入帳號
passwd='your_password', # 密碼
db='my_database', # 目標資料庫
charset='utf8mb4', # 字元集(支援 emoji)
autocommit=False, # 手動控制交易
cursorclass=MySQLdb.cursors.DictCursor # 回傳 dict 而非 tuple
)
| 參數 | 預設值 | 說明 |
|---|---|---|
| host | localhost | 主機名/IP |
| port | 3306 | 埠號 |
| user | 當前系統用戶 | 登入帳號 |
| passwd | 無 | 密碼(必填) |
| db | 無 | 資料庫名(必填) |
| charset | latin1 | **強烈建議 utf8mb4** |
| cursorclass | Cursor | DictCursor 方便欄位名存取 |
| ssl | None | SSL 連線配置字典 |
| connect_timeout | 10 | 連線逾時秒數 |
# 建立游標
cur = conn.cursor()
# CREATE TABLE
cur.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
class VARCHAR(30),
age TINYINT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""")
# INSERT 單筆(參數化防注入)
cur.execute("INSERT INTO students (name, class, age) VALUES (%s, %s, %s)",
('Tom', '3年2班', 9))
# INSERT 多筆(批次高效)
cur.executemany("INSERT INTO students (name, class, age) VALUES (%s, %s, %s)", [
('Jack', '2年1班', 8),
('Mary', '1年3班', 7),
])
# UPDATE
cur.execute("UPDATE students SET class=%s WHERE name=%s", ('3年1班', 'Tom'))
# DELETE
cur.execute("DELETE FROM students WHERE age=%s", (9,))
# SELECT 查詢
cur.execute("SELECT * FROM students WHERE class LIKE %s", ('3年%',))
rows = cur.fetchall() # 取得所有列
for row in rows:
print(f"{row['id']}: {row['name']} - {row['class']} - {row['age']}")
# 交易控制
conn.commit() # 提交
# conn.rollback() # 回滾
# 關閉資源
cur.close()
conn.close()
from DBUtils.PooledDB import PooledDB
pool = PooledDB(
creator=MySQLdb,
maxconnections=20,
mincached=5,
host='localhost', user='root', passwd='pwd', db='mydb', charset='utf8mb4'
)
# 取得連線
conn = pool.connection()
# 用完後 close() 實際歸還池中,不關閉實體連線
with MySQLdb.connect(**config) as conn:
with conn.cursor() as cur:
cur.execute("SELECT VERSION()")
print(cur.fetchone())
# 自動 commit/rollback & close
cur.execute("""
LOAD DATA LOCAL INFILE '/path/data.csv'
INTO TABLE students
FIELDS TERMINATED BY ',' ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(name, class, age)
""")
# 需連線參數 local_infile=True
import aiomysql
async def fetch():
pool = await aiomysql.create_pool(host='localhost', user='root', password='pwd', db='mydb')
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT * FROM students")
return await cur.fetchall()
| 錯誤 | 原因 | 解決 |
|---|---|---|
| ModuleNotFoundError: MySQLdb | 未安裝 mysqlclient | pip install mysqlclient (需 gcc/mysql-devel) |
| Authentication plugin 'caching_sha2_password' not supported | MySQL 8.0 新預設驗證插件 | 帳號改用 mysql_native_password 或升級驅動 |
| OperationalError: (2003, "Can't connect to MySQL server") | 主機/埠/防火牆/服務未啟動 | 檢查 3306 埠、bind-address=0.0.0.0、防火牆規則 |
| UnicodeEncodeError 儲存中文/emoji | 字元集非 utf8mb4 | 連線 charset=utf8mb4、資料庫/表/欄位 CHARSET=utf8mb4 |
專案規模較大時,建議使用 **SQLAlchemy (同步/非同步)** 或 **Tortoise-ORM (異步優先)**,提供:
掌握原生驅動操作是理解 ORM 底層行為的基石,實務中視專案規模選擇適當抽象層級。