如果需要迁移数据库时,目前对于Postgres来说,是比较方便的,有几种方法可以同步数据库数据,我推荐使用 pg_dump 和 psql 命令,这是最可靠的方法:
方法一:使用 pg_dump + psql(推荐)
# 1. 导出源数据库 pg_dump "postgres://testAccount:testPassword@14.103.164.111:5432/synth" > backup.sql # 2. 导入到目标数据库 psql "postgresql://testAccount:testPassword@107.173.129.126:5432/postgres" < backup.sql
方法二:一条命令直接同步
pg_dump "postgres://testAccount:testPassword@14.103.164.111:5432/synth" | psql "postgresql://testAccount:testPassword@107.173.129.126:5432/postgres"
方法三:如果需要更详细的选项
# 导出时包含更多选项 pg_dump -h 14.103.164.111 -U testAccount -d synth -f backup.sql # 导入时使用详细模式 psql -h 107.173.129.126 -U testAccount -d postgres -f backup.sql
注意事项:
- 确保目标数据库存在:如果目标数据库 postgres 不存在,需要先创建
- 权限检查:确保两个数据库的连接权限都正常
- 网络连接:确保能同时访问两个数据库服务器
- 数据冲突:如果目标数据库已有数据,可能需要先清空或使用 --clean 选项
如果需要清空目标数据库再导入:
pg_dump --clean --if-exists "postgres://testAccount:testPassword@14.103.164.111:5432/synth" | psql "postgresql://postgres:postgres@107.173.129.126:5432/postgres"