MySQL Python

用 PyMySQL / SQLAlchemy 在 Python 里操作 MySQL。

Beginner
Key PointsPyMySQL 是纯 Python 驱动;SQLAlchemy 在其上提供 ORM 与连接池。

PyMySQL

Python
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='app',
                       password='***', database='shop',
                       charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
with conn:
    with conn.cursor() as cur:
        cur.execute('SELECT id, username FROM users WHERE age > %s', (25,))
        for row in cur.fetchall():
            print(row['username'])
    conn.commit()
Output
alice
bob

SQLAlchemy

Python
from sqlalchemy import create_engine, text
engine = create_engine('mysql+pymysql://app:***@127.0.0.1/shop?charset=utf8mb4')
with engine.connect() as c:
    rows = c.execute(text('SELECT username FROM users WHERE age > :a'), {'a': 25})
    print([r[0] for r in rows])
In production use SQLAlchemy's pool (pool_size/max_overflow), not a bare connect. ORM reduces SQL, but hand-write SQL for complex reports.

Friends & Partners