配置

允许远程连接

⚠️ 这两个文件在不同操作系统下的路径不同。

我们需要修改两个文件,分别是 postgresql.confpg_hba.conf

  1. postgresql.conf 添加如下内容

    1
    
    listen_addresses = '*'
    
  2. pg_hba.conf 中添加如下内容

    1
    2
    3
    4
    5
    
    # ipv4
    host all all 0.0.0.0/0 md5
    
    # ipv6
    host all all ::0/0 md5
    

FreeBSD

我这里是 postgresql15 的版本

1
vi /var/db/postgres/data15/postgresql.conf
1
vi /var/db/postgres/data15/pg_hba.conf

Ubuntu

1
vi /etc/postgresql/15/main/postgresql.conf
1
vi /etc/postgresql/15/main/pg_hba.conf

连接

使用 psql 远程连接

  1. 使用uri方式
    1
    
    psql postgres://username:password@host:port/dbname  
    
  2. 使用普通的参数方式
    1
    
    psql -U username -h hostname -p port -d dbname 
    

查询

列出所有的数据库名

1
SELECT datname FROM pg_database;

数据库创建操作

创建用户名和密码

1
create user username with encrypted password 'password';

创建新的数据库

1
create database dbname ;

数据库授权操作

1
2
-- 将数据库 dbname 授权给用户 username
grant all privileges on database dbname to username;

备份和恢复

数据库备份和恢复

具体可参考教程

表备份

1
CREATE TABLE new_table AS SELECT * FROM public.old_table;

表数据删除

  1. TRUNCATE 命令(全表数据删除)

    1
    
    TRUNCATE TABLE public.new_table;
    
  2. DELETE 命令

    1
    
    DELETE FROM TABLE WHERE id = 1;