MySQL Python
用 PyMySQL / SQLAlchemy 在 Python 里操作 MySQL。
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
bobSQLAlchemy
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.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
bobSQLAlchemy
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])生产用 SQLAlchemy 的连接池(
pool_size / max_overflow)而非裸连。ORM 映射能少写 SQL,但复杂报表还是直接写 SQL 更可控。