Files
djangoadmin-wiki/DjangoAdmin_Tornado_AntdVue/zh/volume6/db-cross-migrate.md
T
2026-09-16 13:28:20 +08:00

84 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 跨库数据迁移
:::tip 说明
项目提供 `scripts/migrate_db.py` 脚本,支持在不同数据库之间迁移数据(如 MySQL → PostgreSQL / SQL Server / SQLite / Oracle)。脚本独立运行,参数显式给出,不依赖 `.env`。
:::
## 使用场景
| 场景 | 说明 |
|:-----|:-----|
| MySQL → PostgreSQL | 生产环境切换数据库 |
| MySQL → SQL Server | 企业环境适配 |
| MySQL → SQLite | 开发/测试环境轻量化 |
| MySQL → Oracle | 企业级数据库适配 |
## 命令行参数
```bash
python scripts/migrate_db.py --help
```
| 参数 | 必填 | 说明 | 示例 |
|:-----|:-----|:-----|:-----|
| `--source-db` | 是 | 源数据库类型 | `mysql` |
| `--target-db` | 是 | 目标数据库类型 | `postgresql` |
| `--source-url` | 是 | 源数据库连接 URL | `mysql+pymysql://root:123456@localhost:3306/db` |
| `--target-url` | 是 | 目标数据库连接 URL | `postgresql://postgres:123456@localhost:5432/db` |
## 使用示例
### MySQL → PostgreSQL
```bash
python scripts/migrate_db.py \
--source-db mysql \
--target-db postgresql \
--source-url "mysql+pymysql://root:123456@localhost:3306/djangoadmin" \
--target-url "postgresql://postgres:123456@localhost:5432/djangoadmin"
```
### MySQL → SQLite
```bash
python scripts/migrate_db.py \
--source-db mysql \
--target-db sqlite \
--source-url "mysql+pymysql://root:123456@localhost:3306/djangoadmin" \
--target-url "sqlite:///djangoadmin.db"
```
## 迁移流程
```
1. 连接源数据库和目标数据库
2. 读取源数据库所有表结构
3. 在目标数据库创建对应表(Base.metadata.create_all)
4. 逐表读取源数据 → 批量插入目标数据库
5. 输出迁移统计(表数、行数、耗时)
```
## 注意事项
:::warning 迁移前备份
跨库迁移前务必备份目标数据库,避免数据丢失。
:::
- 迁移脚本会先在目标库创建表结构(如已存在则跳过)
- 数据迁移采用批量插入,大表迁移可能需要较长时间
- 不同数据库的字段类型差异由 SQLAlchemy 方言层自动处理
- 迁移完成后建议在目标库执行 `scripts/seed_dict.py` 补充字典数据
## 相关脚本
| 脚本 | 用途 |
|:-----|:-----|
| `scripts/migrate_db.py` | 跨库数据迁移 |
| `scripts/seed_dict.py` | 字典数据初始化 |
| `scripts/init_db.py` | 数据库初始化(建库建表) |
| `scripts/health_check.py` | 健康检查 |
## 总结
跨库数据迁移脚本支持 MySQL / PostgreSQL / SQL Server / SQLite / Oracle 之间的数据迁移,参数显式给出,不依赖 `.env` 配置。迁移前务必备份目标数据库。