CODE/2022-09-15

PostgreSQL 常用命令

提示:以ubuntu系统为例

1、进入数据库容器:

1、查看容器:docker ps 2、进入数据库容器:docker exec -it 容器名称(或 id) bash 3、切换到 postgres 的用户 :sudo su postgres
  • (1)安装 postgresql 会在系统中默认建了一个 postgres 的用户;
  • (2)想“操作数据库”就得切换到这个用户下,才能进行操作;
  • (3)postgres 这个用户是整个数据库的系统管理员;
  • (4)root 用户可以直接:su postgres
plain text_snippet
Plain Text · 6 lines|
[root@i docker]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0000a0000e09 k/pot:latest "/b/sh -c /s…" 7 weeks ago Up 10 days 0.0.0.0:1234->2234/tcp postgres
[root@i docker]# docker exec -it 0000a0000e09 bash
root@0000a0000e09:/scripts# su postgres
postgres@0000a0000e09:/scripts$

2、看当前数据库版本:

plain text_snippet
Plain Text · 2 lines|
postgres@0000a0000e09:/$ psql --version
psql (PostgreSQL) 12.3 (Debian 12.3-1.pgdg100+1)

3、进入数据库:

plain text_snippet
Plain Text · 6 lines|
postgres@0000a0000e09:/$ psql
psql (12.3 (Debian 12.3-1.pgdg100+1))
Type "help" for help.
postgres=#

4、查看所有数据库:

\l (相当于 show database)
plain text_snippet
Plain Text · 8 lines|
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
--------------------+------------+----------+-------------+-------------+-----------------------
test | test | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
(3 rows)

5、切换数据库:

\c + 数据库名 (相当于 mysql 中的,use 数据库)
plain text_snippet
Plain Text · 3 lines|
postgres=# \c test
You are now connected to database "test" as user "postgres".
test=#

6、查看库中表:

plain text_snippet
Plain Text · 5 lines|
test=# \d
List of relations
Schema | Name | Type | Owner
--------+----------------------------------+----------+----------
public | city | table | test

7、创建数据库:

1、创建数据库creat database test1
2、创建数据库,并给指定用户 (1)创建用户
(2)设定库所有者
plain text_snippet
Plain Text · 1 line|
create database 数据库名 owner 用户名;

8、删除数据库:

plain text_snippet
Plain Text · 1 line|
drop database 数据库名 ;
删除完。\l 刚才的创建的数据库就没有了

9、导入数据库:

(1)导入数据库
plain text_snippet
Plain Text · 3 lines|
\q先退出数据库编辑模式 ;
psql -U testuser testdb < /data/backup.sql 用户名和数据库
psql -h localhost -u 用户名 -d 库名 <XXX.bak(数据库文件)
(2)远程连接和导入命令
plain text_snippet
Plain Text · 5 lines|
\q先退出数据库编辑模式 ;
psql -h 主机域名或者ip(例如:localhost) -u 用户名 -d 库名 <XXX.bak(数据库文件)
例如:psql -h postgres.db.com -p 5432 -U testuser -d testdb;
psql -h postgres.db.com -U testuser -d testdb < student.utf8.sql

10、退出数据库:

plain text_snippet
Plain Text · 4 lines|
test-# \q
could not save history to file "/v": No such file or directory
postgres@0000a0000e09:/$
COMPANION ESSAYS / 思想脉络与互照篇目
同卷深读2026-05-22 ·

python3安装在centos详细教程

同属「系统工程卷」脉络衍生思考与工程推演推演阅读 →
跨界互照2026-08-22 ·

我的书架:03|金融经管:经济运行、金融体系与企业治理

我的书架:03|金融经管:经济运行、金融体系与企业治理

跨领域对照思辨 · 从「思想随笔」视界互为印证推演阅读 →
RELATED INDEX / 相关阅读索引
柯航hang.ke·© 2014—2026
CC BY-NC 4.0·