PostgreSQL CLI 基础指南 | AI生成和翻译

Home 2026.02

PostgreSQL 提供了多种 command-line utilities,每种都有丰富的选项。以下是关于最重要工具的全面指南。

psql (Interactive Terminal)

psql 命令是与 PostgreSQL 数据库交互的主要 interface。

Connection Options:

Output Options:

Behavior Options:

Example:

psql -h localhost -U postgres -d mydb -c "SELECT * FROM users LIMIT 5"

pg_dump (Backup Utility)

创建数据库的 backup 副本。

General Options:

Output Format:

Selective Dumping:

Compression:

Example:

pg_dump -h localhost -U postgres -d mydb -F c -f mydb_backup.dump

pg_restore (Restore Utility)

从 pg_dump 创建的 backups 中还原数据库。

Connection Options:

Restore Options:

Selective Restore:

Example:

pg_restore -h localhost -U postgres -d mydb -c mydb_backup.dump

createdb / dropdb

快速创建和删除数据库的 utilities。

createdb Options:

Example:

createdb -h localhost -U postgres -O myuser mynewdb
dropdb -h localhost -U postgres olddb

createuser / dropuser

用户管理 utilities。

createuser Options:

Example:

createuser -h localhost -U postgres -d -P newuser

pg_isready

检查与 PostgreSQL 服务器的连接状态。

Options:

Example:

pg_isready -h localhost -p 5432

Common Patterns

连接到远程数据库:

psql -h db.example.com -p 5432 -U admin -d production

创建一个压缩的 backup:

pg_dump -h localhost -U postgres -d mydb -F c -Z 9 -f backup.dump

仅 dump 一张表:

pg_dump -h localhost -U postgres -d mydb -t users -f users.sql

还原到不同的数据库名称:

createdb newdb
pg_restore -h localhost -U postgres -d newdb backup.dump

从文件运行 SQL:

psql -h localhost -U postgres -d mydb -f schema.sql

设置环境变量以避免重复:

export PGHOST=localhost
export PGPORT=5432
export PGUSER=postgres
export PGDATABASE=mydb

psql  # 现在会自动连接

大多数 PostgreSQL utilities 也会遵循 PGPASSWORD 环境变量,尽管在生产环境中使用 .pgpass 文件更加安全。


Back Donate