今天詳細(xì)講解一下在 Python 中連接 MySQL 數(shù)據(jù)庫的幾種主流方法。這將是一個從基礎(chǔ)到進(jìn)階的完整指南。
在 Python 中連接 MySQL,主要有兩個流行的驅(qū)動:
1. mysql-connector-python: MySQL 官方提供的純 Python 驅(qū)動。無需其他依賴,安裝簡單。
2. PyMySQL: 一個純 Python 的 MySQL 客戶端,兼容性很好,非常流行。
3. (底層驅(qū)動) MySQLdb: 一個 C 擴(kuò)展模塊,速度很快,但在 Python 3 上安裝可能較麻煩,通常被 PyMySQL 替代。
對于現(xiàn)代項(xiàng)目,PyMySQL 和 mysql-connector-python 是最常見的選擇。本指南將以 `PyMySQL` 和 `SQLAlchemy` 為例。
方法一:使用 PyMySQL 直接連接(基礎(chǔ)方法)
這種方式提供了最直接的 SQL 操作,適合需要完全控制 SQL 語句的場景。
完整的操作流程遵循 連接 -> 創(chuàng)建游標(biāo) -> 執(zhí)行SQL -> 提交 -> 關(guān)閉 的步驟。
from pymysql.cursors import DictCursor 可選,用于獲取字典格式的結(jié)果
connection = pymysql.connect(
host='localhost', 數(shù)據(jù)庫服務(wù)器地址,本地可用 localhost 或 127.0.0.1
user='your_username', 用戶名
password='your_password', 密碼
database='your_database_name', 要連接的數(shù)據(jù)庫名
charset='utf8mb4', 字符集,支持中文和表情符號推薦 utf8mb4
cursorclass=DictCursor 可選:設(shè)置游標(biāo)類型,返回字典而非元組
2. 創(chuàng)建一個游標(biāo)對象,用于執(zhí)行SQL語句
with connection.cursor() as cursor:
sql = "SELECT `id`, `name` FROM `users` WHERE `email` = %s"
cursor.execute(sql, ('user@example.com',)) 使用參數(shù)化查詢,防止SQL注入!
result = cursor.fetchone() 獲取單條記錄
print(result) 如果是DictCursor,輸出: {'id': 1, 'name': 'John'}
如果用默認(rèn)游標(biāo),輸出: (1, 'John')
results = cursor.fetchall()
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`name`, `email`) VALUES (%s, %s)"
cursor.execute(sql, ('Alice', 'alice@example.com'))
3. 提交事務(wù)!對于INSERT/UPDATE/DELETE等寫操作,必須提交才會生效。
示例3: 獲取剛插入數(shù)據(jù)的主鍵ID
with connection.cursor() as cursor:
sql = "INSERT INTO `users` (`name`, `email`) VALUES (%s, %s)"
cursor.execute(sql, ('Bob', 'bob@example.com'))
print(f"新插入記錄的ID是: {cursor.lastrowid}")
為了確保連接總是能被正確關(guān)閉,即使發(fā)生異常,推薦使用 `with` 語句。
使用 with 語句自動管理連接和游標(biāo)的關(guān)閉
with pymysql.connect(host='localhost', user='root', password='password', database='test') as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT VERSION()")
result = cursor.fetchone()
print(f"Database version: {result[0]}")
連接結(jié)束時,如果沒有異常,會自動 commit(); 如果有異常,會自動 rollback()
except pymysql.Error as e:
print(f"Database error: {e}")
方法二:使用 SQLAlchemy (ORM 框架,進(jìn)階方法)
ORM (Object-Relational Mapping) 允許你使用 Python 類和對象來操作數(shù)據(jù)庫,而不是直接寫 SQL。這對于大型、復(fù)雜的項(xiàng)目非常有益,可以提高開發(fā)效率和代碼可維護(hù)性。
pip install sqlalchemy pymysql
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
格式: dialect+driver://username:password@host:port/database
DB_URI = 'mysql+pymysql://username:password@localhost:3306/your_database?charset=utf8mb4'
2. 創(chuàng)建引擎 (Engine),它是ORM和數(shù)據(jù)庫的連接核心
engine = create_engine(DB_URI, echo=True) echo=True 會打印執(zhí)行的SQL,調(diào)試時有用
Base = declarative_base()
__tablename__ = 'users' 指定映射的表名
id = Column(Integer, primary_key=True, autoincrement=True)
name = Column(String(50), nullable=False)
email = Column(String(100), unique=True)
Base.metadata.create_all(engine)
6. 創(chuàng)建會話工廠 (Session)
Session = sessionmaker(bind=engine)
with Session() as session:
new_user = User(name='Charlie', email='charlie@example.com')
session.commit() 提交事務(wù)
print(f"New user ID: {new_user.id}") 提交后,id自動賦值
with Session() as session:
users = session.query(User).all()
print(user.id, user.name, user.email)
user = session.query(User).filter_by(name='Charlie').first()
print(f"Found user: {user.name}")
1. 安全第一:永遠(yuǎn)使用參數(shù)化查詢
錯誤做法(SQL注入風(fēng)險): `cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'")`
正確做法: `cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))`
PyMySQL 使用 `%s` 作為占位符,即使數(shù)據(jù)是數(shù)字或日期。
切勿將數(shù)據(jù)庫密碼等硬編碼在代碼中!
使用環(huán)境變量或配置文件(如 `.env` 文件)來管理。
pip install python-dotenv
DB_PASSWORD=your_secure_password
from dotenv import load_dotenv
load_dotenv() 加載 .env 文件中的環(huán)境變量
connection = pymysql.connect(
host=os.getenv('DB_HOST'),
user=os.getenv('DB_USER'),
password=os.getenv('DB_PASSWORD'),
database=os.getenv('DB_NAME')
數(shù)據(jù)庫連接是昂貴的資源,一定要確保在使用后正確關(guān)閉。強(qiáng)烈推薦使用 `with` 語句上下文管理器。
簡單腳本、需要精細(xì)控制SQL:選擇 PyMySQL 或 mysql-connector-python。
Web應(yīng)用、復(fù)雜業(yè)務(wù)邏輯、希望代碼更Pythonic:選擇 SQLAlchemy ORM。
另外搭配便捷的MYSQL備份工具,可定時備份、異地備份,MYSQL導(dǎo)出導(dǎo)入。可本地連接LINUX里的MYSQL,簡單便捷。可以大大地提高工作效率喔。