在 CentOS 上“导入 PostgreSQL 数据”通常有几类常见场景,下面按最常用方式给你说明,你可以根据自己的情况选择。
psql 导入 SQL 文件(最常见)例如:
/backup/db.sql
psql -U username -d dbname -h localhost -f /backup/db.sql
示例:
psql -U postgres -d testdb -f /backup/testdb.sql
如果提示密码,请输入对应用户密码
或提前配置~/.pgpass
pg_restore 导入备份文件(.dump / .tar)如果是用 pg_dump -F c 或 -F t 生成的备份:
pg_restore -U username -d dbname /backup/db.dump
示例:
pg_restore -U postgres -d testdb /backup/testdb.dump
常用参数:
pg_restore -U postgres -d testdb --clean --if-exists /backup/testdb.dump
--clean:先删除已有对象--if-exists:避免报错COPY table_name FROM '/path/to/file.csv' WITH (FORMAT csv, HEADER true);
或在 shell 中:
psql -U postgres -d testdb -c "\copy table_name FROM '/path/file.csv' WITH CSV HEADER"
⚠️ 注意:
COPY 需要 PostgreSQL 服务端权限\copy 是客户端导入,更安全常见方式:
pgloader(推荐)示例(pgloader):
pgloader mysql://user:pwd@host/db postgresql://user:pwd@localhost/db
# 登录
psql -U postgres
# 创建数据库
CREATE DATABASE testdb;
# 创建用户
CREATE USER testuser WITH PASSWORD '123456';
# 授权
GRANT ALL PRIVILEGES ON DATABASE testdb TO testuser;
which psql
若没有:
yum install postgresql-client
或
dnf install postgresql
如果你能告诉我:
我可以给你更精确的一步一步命令。