Docker运行MySQL

mkdir -p /data/mysql
docker run -d \
  --name my-mysql \
  -e MYSQL_ROOT_PASSWORD=123456 \
  -e MYSQL_DATABASE=mysql_bear \
  -p 3306:3306 \
  -v /data/mysql:/var/lib/mysql \
  mysql:8.0

需要另外安装这两个Python库

pip install PyMySQ
pip install cryptography

启动 MySQL 容器时务必加上卷挂载, 这样你的数据库文件会保存在主机 /data/mysql 中

import os
import pandas as pd
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import declarative_base

Base = declarative_base()

# MySQL Docker 连接
engine = create_engine(
    "mysql+pymysql://root:123456@127.0.0.1:3306/mysql_bear",
    pool_pre_ping=True,
    pool_recycle=3600,
    echo=True,
)

# SQLite 数据库路径
sqlite_db = "./sqlite_01.db"
if not os.path.exists(sqlite_db):
    raise FileNotFoundError(f"{sqlite_db} 不存在")

# 创建 SQLite 引擎
sqlite_engine = create_engine(f"sqlite:///{sqlite_db}")

# 1. 在 MySQL 中创建表结构
Base.metadata.create_all(engine)
print("✅ MySQL 表结构创建完成")

# 2. 获取 SQLite 所有表名(SQLAlchemy 2.0 新写法)
inspector = inspect(sqlite_engine)
tables = inspector.get_table_names()
print(f"发现表: {tables}")

# 3. 逐表迁移
for table in tables:
    print(f"正在迁移表: {table}")
    df = pd.read_sql_table(table, sqlite_engine)
    df.to_sql(table, engine, if_exists="replace", index=False)
    print(f"✅ {table} 迁移完成 ({len(df)} 条记录)")

print("🎉 SQLite 数据已成功迁移到 MySQL!")

运行上面的Python代码

在这里插入图片描述

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐