debian

Debian上PostgreSQL数据库迁移方法

小樊
55
2025-09-01 11:02:42
栏目: 云计算

以下是Debian上PostgreSQL数据库的常见迁移方法及步骤:

一、使用pg_dump/pg_restore(官方推荐)

适用场景:跨服务器/跨版本迁移、逻辑备份恢复。

  1. 备份源数据库
    sudo -u postgres pg_dump -U username -F t -f backup.tar source_database  
    
    • -F t:指定tar格式备份。
  2. 传输备份文件
    scp backup.tar user@target_server:/path/to/destination/  
    
  3. 恢复到目标数据库
    sudo -u postgres psql -d target_database -f /path/to/destination/backup.tar  
    
    • 若需创建新数据库,先执行:sudo -u postgres createdb target_database

二、使用pgloader(支持异构迁移)

适用场景:从MySQL/Oracle等迁移至PostgreSQL。

  1. 安装pgloader
    sudo apt-get install pgloader  
    
  2. 创建配置文件(如migration.load
    LOAD DATABASE  
      FROM mysql://user:pass@host/source_db  
      INTO postgresql://user:pass@host/target_db  
      WITH include drop, create tables, reset sequences  
    
  3. 执行迁移
    pgloader migration.load  
    

三、使用COPY命令(适合结构化数据)

适用场景:导入CSV/TSV等结构化数据文件。

  1. 准备数据文件(如data.csv)。
  2. 导入数据
    cat data.csv | psql -U username -d target_db -c "COPY table_name FROM STDIN WITH CSV HEADER"  
    
    • 或直接在SQL文件中使用:COPY table_name FROM '/path/to/data.csv' WITH CSV HEADER

四、注意事项

参考来源

0
看了该问题的人还看了