在WSL2-Ubuntu22.04上配置Postgresql环境

安装PostgreSQL环境

sudo apt update
sudo apt install postgresql postgresql-contrib

确认版本

psql --version
>>> psql (PostgreSQL) 14.8 (Ubuntu 14.8-0ubuntu0.22.04.1)

PostgreSQL的使用方法

启动

sudo service postgresql start

查询状态

sudo service postgresql status
>>> * Starting PostgreSQL 14 database server   [ OK ]

请使用Postgres登录

sudo -u postgres -i 
postgres@DESKTOP-29D8DSQ:~$ psql
psql (14.8 (Ubuntu 14.8-0ubuntu0.22.04.1))
Type "help" for help.

postgres=#

数据库列表

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

角色列表

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

在SuperUser上创建角色

postgres=# CREATE ROLE <new_name> WITH SUPERUSER LOGIN PASSWORD '<pass>';
CREATE ROLE
postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 new_name  | Superuser                                                  | {}
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

创建一个新的数据库,角色是所有者。

postgres=# CREATE DATABASE <db_name> WITH OWNER <ubuntu_name>;
CREATE DATABASE
postgres-# \l
                                 List of databases
    Name    |     Owner     | Encoding | Collate |  Ctype  |   Access privileges
------------+---------------+----------+---------+---------+-----------------------
 <db_name>  | <ubuntu_name> | UTF8     | C.UTF-8 | C.UTF-8 |
 postgres   | postgres      | UTF8     | C.UTF-8 | C.UTF-8 |
 template0  | postgres      | UTF8     | C.UTF-8 | C.UTF-8 | =c/postgres          +
            |               |          |         |         | postgres=CTc/postgres
 template1  | postgres      | UTF8     | C.UTF-8 | C.UTF-8 | =c/postgres          +
            |               |          |         |         | postgres=CTc/postgres

指定角色连接到数据库。

psql <ubuntu_name> -d <db_name>
psql (14.8 (Ubuntu 14.8-0ubuntu0.22.04.1))
Type "help" for help.

analysis=#

停止可以改成以下方式:
– 终止
– 结束
– 中止
– 暂停
– 停下

sudo service postgresql stop
>>> * Stopping PostgreSQL 14 database server     [ OK ]

你可以参考以下网站

 

bannerAds