of {$slidecount} ½ {$title} ATZJG.NET {$author}

首页






PostgreSQL 的安装
数据库原理及应用实验


Haifeng Xu


(hfxu@yzu.edu.cn)

References:

目录

历史

PostgreSQL的历史

PostgreSQL 最初称为 Postgres, 是由一位名叫 Michael Stonebraker 的计算机教授在加州大学伯克利分校(UCB)开发的.

1986年, 他启动了一个名为Ingres的项目. 这是 Postgres 的前身.

安装 PostgreSQL

安装 PostgreSQL

到 PostgreSQL 官方网站 https://www.postgresql.org/download/ 下载最新的稳定版本. Windows 下的安装相比 Linux 要简单很多.

具体安装过程

安装完成后

安装完成之后, 建议将 "C:\Program Files\PostgreSQL\17\bin\" 加入到环境变量 PATH 中. 这样在命令窗口中就可以直接运行 psql 命令了.

Windows 下, 在命令行窗口输入下面的命令即可打开环境变量编辑页面.

rundll32 sysdm.cpl,EditEnvironmentVariables

不过只能编辑当前用户的环境变量. 若要新建或编辑系统环境变量, 则需要管理员运行 PowerShell 并执行上面的命令.

Linux 下安装 PostgreSQL

Ubuntu

第一步, 更新包索引

在安装之前, 确保安装包列表是最新的.

ubuntu@VM-0-13-ubuntu:~$ sudo apt update
Hit:1 http://mirrors.tencentyun.com/ubuntu jammy InRelease
Hit:2 http://mirrors.tencentyun.com/ubuntu jammy-updates InRelease
Hit:3 http://mirrors.tencentyun.com/ubuntu jammy-security InRelease
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
284 packages can be upgraded. Run 'apt list --upgradable' to see them.

第二步: 安装 PostgreSQL

sudo apt install postgresql postgresql-contrib
ubuntu@VM-0-13-ubuntu:~$ sudo apt install postgresql postgresql-contrib
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  libcommon-sense-perl libjson-perl libjson-xs-perl libllvm14 libpq5 libsensors-config libsensors5
  libtypes-serialiser-perl postgresql-14 postgresql-client-14 postgresql-client-common postgresql-common sysstat
Suggested packages:
  lm-sensors postgresql-doc postgresql-doc-14 isag
The following NEW packages will be installed:
  libcommon-sense-perl libjson-perl libjson-xs-perl libllvm14 libpq5 libsensors-config libsensors5
  libtypes-serialiser-perl postgresql postgresql-14 postgresql-client-14 postgresql-client-common
  postgresql-common postgresql-contrib sysstat
0 upgraded, 15 newly installed, 0 to remove and 284 not upgraded.
Need to get 42.5 MB of archives.
After this operation, 162 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

第三步: 验证安装

sudo systemctl status postgresql
ubuntu@VM-0-13-ubuntu:~$ sudo systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
     Active: active (exited) since Fri 2025-09-05 12:36:00 CST; 7min ago
    Process: 1539254 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 1539254 (code=exited, status=0/SUCCESS)
        CPU: 1ms

Sep 05 12:36:00 VM-0-13-ubuntu systemd[1]: Starting PostgreSQL RDBMS...
Sep 05 12:36:00 VM-0-13-ubuntu systemd[1]: Finished PostgreSQL RDBMS.

如果状态是 inactive (dead), 如下

○ postgresql.service - PostgreSQL database server
     Loaded: loaded (/usr/lib/systemd/system/postgresql.service; disabled; preset: disabled)
     Active: inactive (dead)

则需要输入命令 sudo systemctl start postgresql 启动 PostgreSQL 服务.

第四步: 登录 PostgreSQL

切换到 postgresql 用户, 并运行 psql 命令.

ubuntu@VM-0-13-ubuntu:~$ sudo -i -u postgres
postgres@VM-0-13-ubuntu:~$ 
postgres@VM-0-13-ubuntu:~$ psql
psql (14.18 (Ubuntu 14.18-0ubuntu0.22.04.1))
Type "help" for help.

postgres=# 

使用 \l 命令列出所有数据库, 然后使用命令 \q 退出 PostgreSQL. 注意退出后, 仍处于 Linux 用户 postgres 登录界面, 使用 exit 命令可以登出.

postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
           |          |          |             |             | postgres=CTc/postgres
(3 rows)

postgres=# \q
postgres@VM-0-13-ubuntu:~$ exit
logout
ubuntu@VM-0-13-ubuntu:~$

Local Notes

安装 Local Notes

Local Notes 集成了 Nginx, PHP 和 PostgreSQL.

因此可以安装 Local Notes.

文档

文档

假设 PostgreSQL 默认安装在 C:/Program Files 目录, 则本地文档首页位于 file:///C:/Program%20Files/PostgreSQL/17/doc/src/sgml/html/index.html

中文手册见 http://www.postgres.cn/docs/current/index.html

PDF 版本下载见 https://www.postgresql.org/docs/

登录 PostgreSQL

登录 PostgreSQL

使用 psql 命令登录 postgresql, 语法是

psql -hlocalhost -Upostgres -p5432 -dDBNAME

参数 -h 等后面可以跟空格.

psql -h localhost -U postgres -p 5432
PS C:\Users\haife> psql -Upostgres
用户 postgres 的口令:

psql (17.6)
输入 "help" 来获取帮助信息.

使用 postgres 用户登录指定的数据库 template1. 这里甚至不需要加 -d 参数.

PS C:\Users\haife> psql -Upostgres template1
用户 postgres 的口令:

psql (17.6)
输入 "help" 来获取帮助信息.

template1=#

注意, 如果仅输入 psql 并回车, 则默认用户名为当前操作系统下的当前用户. 例如,

PS C:\Users\haife> psql
用户 haife 的口令:

连接数据库或切换数据库

连接数据库或切换数据库

首先使用命令 \l 列出所有数据库的名称以及拥有者等信息.

postgres=# \l
                                                    数据库列表
   名称    |  拥有者  | 字元编码 | Locale Provider | 校对规则 | Ctype | Locale | ICU Rules |       存取权限
-----------+----------+----------+-----------------+----------+-------+--------+-----------+-----------------------
 postgres  | postgres | UTF8     | libc            | zh-CN    | zh-CN |        |           |
 template0 | postgres | UTF8     | libc            | zh-CN    | zh-CN |        |           | =c/postgres          +
           |          |          |                 |          |       |        |           | postgres=CTc/postgres
 template1 | postgres | UTF8     | libc            | zh-CN    | zh-CN |        |           | =c/postgres          +
           |          |          |                 |          |       |        |           | postgres=CTc/postgres
(3 行记录)

另一种方法是查看 pg_catalog.pg_database 中的信息.

postgres=# SELECT datname FROM pg_catalog.pg_database;
     datname
-----------------
 postgres
 template1
 template0
 mydb
 new_db
 postgresql_book
 testbar
(7 行记录)

使用命令 \c 连接到 template1 数据库. 注意无法连接 template0 数据库.

postgres=# \c template1
您现在已经连接到数据库 "template1",用户 "postgres".
template1=# \c template0
连接到"localhost" (::1)上的服务器,端口5432失败:致命错误:  数据库 "template0" 当前不接受联接
保留上一次连接

template1=# \c postgres
您现在已经连接到数据库 "postgres",用户 "postgres".

这里命令 \c 中的 c 是 connect 的意思, 类似于 MySQL 中的 use 命令, 用于切换数据库.

命令 \conninfo 可以显示当前连接的相关信息.

postgres=# \conninfo
以用户 "postgres" 的身份, 在主机"localhost" (地址 "::1"), 端口"5432"连接到数据库 "postgres".

常用命令

常用命令

上面已经用到了几个常用的命令, 例如 \l, \c, \conninfo 等. 若退出PostgreSQL, 则使用 \q 命令.

help 命令会显示下面的提示信息, \? 会列出 pgsql 命令的信息.

postgres=# help
您正在使用psql, 这是一种用于访问PostgreSQL的命令行界面.
键入: \copyright 显示发行条款
       \h 显示 SQL 命令的说明
       \? 显示 pgsql 命令的说明
       \g 或者以分号(;)结尾以执行查询
       \q 退出

创建用户

创建用户

我们已经看到 PostgreSQL 安装后有一个默认的用户 postgres. 这是一个超级用户, 拥有所有权限. 如果使用不当, 会对系统造成非常大的危害, 因此需要创建普通角色用户.

创建新用户的语法为

CREATE USER your_name WITH PASSWORD 'your_passwd';

为方便起见, 为刚才操作系统用户 haife 创建一个 PostgreSQL 账户.

postgres=# CREATE USER haife WITH PASSWORD 'postgresql';
CREATE ROLE

跟 MySQL 不一样, 此时尚不能使用新创建的用户 haife 登录 PostgreSQL.

PS C:\Users\haife> psql -h localhost -U haife -p 5432
用户 haifeng 的口令:

psql: 错误: 连接到"localhost" (::1)上的服务器,端口5432失败:致命错误:  数据库 "haife" 不存在

如上所述, 该用户尚未拥有数据库, 即使同名的数据库也不存在.

重新用 postgres 登录 PostgreSQL, 使用 \du 命令列出所有用户.

postgres=# \du
                       角色列表
 角色名称 |                    属性
----------+--------------------------------------------
 haife    |
 postgres | 超级用户, 建立角色, 建立 DB, 复制, 绕过RLS

命令 \du+ 会显示额外的信息(描述).

postgres=# \du+
                           角色列表
 角色名称 |                    属性                    | 描述
----------+--------------------------------------------+------
 haife    |                                            |
 postgres | 超级用户, 建立角色, 建立 DB, 复制, 绕过RLS |

创建数据库

创建数据库

为给新用户 haife 授权, 或者使用该账号登录 PostgreSQL, 需先创建一个数据库, 并令其有一定的控制权.

我们创建一个名为 sowya 的数据库.

template1=# CREATE DATABASE sowya;
CREATE DATABASE

给新建的用户授权

给新建的用户授权

现在将数据库 sowya 的所有权限授予用户 haife.

template1=# GRANT ALL PRIVILEGES ON DATABASE sowya TO haife;
GRANT

键入 \q 退出 PostgreSQL. 并使用账号 haife 登录数据库 sowya.

PS C:\Users\haife> psql -d sowya
用户 haife 的口令:

psql (17.6)
输入 "help" 来获取帮助信息.

sowya=>

配置文件

PostgreSQL的配置文件

Linux 下的配置文件一般保存在 /etc/postgresql/ 下, 例如上面安装的 14 版本, 其配置文件所在目录为 /etc/postgresql/14/main/, 其中有若干个 .conf 文件.

ubuntu@VM-0-13-ubuntu:/etc/postgresql/14/main$ ls
conf.d  environment  pg_ctl.conf  pg_hba.conf  pg_ident.conf  postgresql.conf  start.conf

更改用户密码

更改用户密码

Linux 下初次安装 PostgreSQL 后, 超级用户 postgres 的密码默认是空的.

ubuntu@VM-0-13-ubuntu:~$ sudo -i -u postgres
postgres@VM-0-13-ubuntu:~$ psql -U postgres
psql (14.18 (Ubuntu 14.18-0ubuntu0.22.04.1))
Type "help" for help.

postgres=# 

更新 postgres 用户的密码

postgres=# ALTER USER postgres WITH PASSWORD 'newpassword';

\q 退出, 然后重启 postgresql 服务.

ubuntu@VM-0-13-ubuntu:~$ sudo service postgresql restart

使用密码登录

ubuntu@VM-0-13-ubuntu:~$ psql -h localhost -Upostgres
Password for user postgres: 
psql (14.18 (Ubuntu 14.18-0ubuntu0.22.04.1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=#

列出当前所有用户.

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

postgres=# \du+
                                          List of roles
 Role name |                         Attributes                         | Member of | Description 
-----------+------------------------------------------------------------+-----------+-------------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}        | 

Local Notes

在 Local Notes 中登录数据库

首先双击桌面上的 Local Notes 的快捷方式.

出现如下对话框

点击 start, 这将启动 Nginx, PHP 和 PostgreSQL.

点击后会显示 Nginx has been started.

到 Local Notes 的安装目录, 找到 PostgreSQL 中 PgAdmin 4 的安装目录, 然后启动 PgAdmin 4.

C:\lnotes\pgsql\pgAdmin 4\bin>pgAdmin4.exe

默认是英文界面.

我们将其语言设置为中文. 点击 File >> Preferences

点击左侧栏中的 User language, 选择 Chinese (Simplified), 然后点击 OK 保存.

点击 File >> Reset Layout .

在弹出的 Reset layout 确认对话框中点击 OK 就会呈现中文界面了.

点击左侧 Servers 下面的 LocalNotes 服务器, 弹出【连接到服务器】对话框. 这里使用默认用户 postgres 登录, 密码为空. 因此只要点击【好】即可登录.

页面显示如下. 你可以依次点击右边的[仪表板]、[属性]、[SQL]、[统计信息]、[依赖关系] 和 [依赖组件]。它们是相应于当前左侧边栏中的 LocalNotes 对象的. 以后右侧显示的信息都是针对左侧边栏中选定对象的.

将左侧边栏中, 点击 LocalNotes 下面的[数据库]前面的 + 号,

我们新建一个数据库, 名为 test_bar. 为此, 右键点击左侧边栏中的[数据库], 点击[创建]>>[数据库]

弹出的【创建-数据库】对话框

在[通常]选项卡的[数据库]一栏填写名称 test_bar

在[安全]选项卡中, 可以按如下图所示选择

类似的, 在[参数]选项卡中, 设置变量 application_name 的值为 DEFAULT.

点击 [SQL] 选项卡, 可以看到整个过程等同于最后要执行的 SQL 代码.

点击【保存】, 在左侧可以看到新增的数据库 test_bar.

点击 test_bar 左侧的 + 号.

然后点击右侧的[SQL], 可以看到详细的 SQL 代码.

常见错误

常见错误

haifeng@LAPTOP-Q34L5TP8:~> psql -U postgres
psql: error: connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
        Is the server running locally and accepting connections on that socket?

PostgreSQL 可能未启动, 请输入 sudo systemctl start postgresql 启动 PostgreSQL 服务.

当然也可能启动了, 但是未在接听状态. 请检查端口号是否设置正确.


haifeng@LAPTOP-Q34L5TP8:~> psql -Upostgres
psql: error: connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: FATAL:  Peer authentication failed for user "postgres"

用户 "postgres" 的 Peer 身份验证失败. 在PostgreSQL中, Peer身份验证是一种针对本地连接的身份验证方法. 默认情况下, 它使用操作系统的用户和组来验证PostgreSQL的用户身份. 当出现上述错误消息时, 这意味着系统用户和PostgreSQL用户之间存在不匹配或未正确配置的问题.

注意: Peer身份验证通常只适用于本地连接.

haifeng@LAPTOP-Q34L5TP8:~> psql
psql: error: connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: FATAL:  role "haifeng" does not exist

这里提到用户(角色) "haifeng" 不存在. 注意 haifeng 是 Linux 的登录名. 而 PostgreSQL 的用户账户与操作系统的用户账户是不同的. 产生这个错误的原因是 PostgreSQL 的管理员没有为 Linux 用户 "haifeng" 创建一个属于 PostgreSQL 的用户账户.

postgres=# \du
                             List of roles
 Role name |                         Attributes
-----------+------------------------------------------------------------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS

End






Thanks very much!