Python连接MySQL数据库

使用 python 3.10 连接 MySQL 8.0 数据库

安装 peewee

Peewee 是一个轻量级的 Python ORM(对象关系映射)库,它让您可以用 Python 代码来操作数据库,而不需要直接写 SQL 语句。

1
mamba install peewee

安装 pymysql

1
mamba install pymysql
1
2
3
4
5
6
7
Python 代码

Peewee ORM

PyMySQL 驱动

MySQL 数据库

数据库连接

1
2
3
import peewee
db = peewee.MySQLDatabase("vnpy", user="root", password="password", host="127.0.0.1", port=3306)
db.connect()

后来发现使用 SQLAlchemy 也不错。

写一个使用 SQL 查询的案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from sqlalchemy import create_engine, text

# 创建数据库引擎
engine = create_engine('mysql+pymysql://root:password@localhost:3306/ticket_system')

with engine.connect() as connection:
# 使用命名参数
sql_with_params = text("""
SELECT id, title, status, create_time
FROM ticket
WHERE status = :status
AND create_time >= :start_date
ORDER BY create_time DESC
LIMIT :limit_num
""")

params = {
"status": "PENDING",
"start_date": "2020-01-01",
"limit_num": 5
}

result = connection.execute(sql_with_params, params)
print("参数化查询结果:")
for row in result:
print(f"ID: {row.id}, 标题: {row.title}, 时间: {row.create_time}")