温馨提示×

centos如何导入postgresql数据

小樊
41
2026-09-03 08:33:52
栏目: 云计算

CentOS 上导入 PostgreSQL 数据,常见有几种方式,取决于你的数据来源(SQL 文件、dump 文件、CSV 等)。下面按最常用场景说明。


一、准备工作

1. 安装 PostgreSQL 客户端(如未安装)

sudo yum install -y postgresql

如果你用的是 PostgreSQL 12+:

sudo dnf install -y postgresql

2. 确认数据库和服务

systemctl status postgresql

切换为 postgres 用户:

sudo -u postgres psql

二、导入 SQL 文件(最常见)

方式 1:使用 psql 导入

psql -U username -d dbname -h localhost -f /path/to/file.sql

示例:

psql -U postgres -d testdb -f /home/user/data.sql

如果是 postgres 用户本地导入:

sudo -u postgres psql -d testdb -f /home/user/data.sql

方式 2:在 psql 内部导入

\i /path/to/file.sql

三、导入 pg_dump 备份文件

1. 自定义格式(.dump)

pg_restore -U postgres -d testdb /path/to/backup.dump

2. 纯文本格式

psql -U postgres -d testdb -f backup.sql

四、导入 CSV 文件

假设表结构已存在:

COPY table_name FROM '/path/to/file.csv' WITH CSV HEADER;

⚠️ 注意:

  • 文件必须能被 postgres 用户读取
  • 最好放在 /tmp 或数据库可访问目录

五、新建数据库后再导入

sudo -u postgres createdb testdb
sudo -u postgres psql -d testdb -f data.sql

六、常见问题

1. 权限错误

chown postgres:postgres file.sql
chmod 600 file.sql

2. 编码问题

export PGCLIENTENCODING=UTF8

3. 远程导入

psql -h 192.168.1.10 -U postgres -d dbname -f file.sql

如果你能说明:

  • 数据格式(SQL / dump / CSV)
  • PostgreSQL 版本
  • 是否远程服务器

我可以给你更精确的命令

0