如何实现mysql表数据转postgresql

流程图

flowchart TD
    A[连接到MySQL数据库] --> B[导出MySQL表结构]
    B --> C[创建相同结构的表在PostgreSQL]
    C --> D[将数据从MySQL导入PostgreSQL]

任务步骤

步骤 描述
1 连接到MySQL数据库
2 导出MySQL表结构
3 创建相同结构的表在PostgreSQL
4 将数据从MySQL导入PostgreSQL

1. 连接到MySQL数据库

# 连接到MySQL数据库

# 导入必要的库
import pymysql

# 建立连接
conn = pymysql.connect(host='localhost', user='username', password='password', database='dbname')

# 获取游标
cursor = conn.cursor()

# 提示连接成功
print('连接到MySQL数据库成功')

2. 导出MySQL表结构

# 导出MySQL表结构

# 查询表结构
cursor.execute('SHOW CREATE TABLE tablename')
results = cursor.fetchall()

# 打印表结构
for result in results:
    print(result[1])

3. 创建相同结构的表在PostgreSQL

# 创建相同结构的表在PostgreSQL

# 导入必要的库
import psycopg2

# 建立连接
conn_postgresql = psycopg2.connect(host='localhost', user='username', password='password', database='dbname')

# 获取游标
cursor_postgresql = conn_postgresql.cursor()

# 创建表
cursor_postgresql.execute('CREATE TABLE tablename (column1 datatype1, column2 datatype2, ...)')
print('创建PostgreSQL表成功')

4. 将数据从MySQL导入PostgreSQL

# 将数据从MySQL导入PostgreSQL

# 查询MySQL数据
cursor.execute('SELECT * FROM tablename')
results = cursor.fetchall()

# 插入数据到PostgreSQL
for result in results:
    cursor_postgresql.execute('INSERT INTO tablename VALUES (%s, %s, ...)', result)

# 提交更改
conn_postgresql.commit()

# 提示导入成功
print('数据导入PostgreSQL成功')

结尾

通过以上步骤,你可以成功将MySQL表数据转移到PostgreSQL,并保留原始表结构。希望本文对你有所帮助,如有疑问请随时联系我。祝一切顺利!