PostgreSQL14.0入门安装使用

1.安装

1.系统版本CentOS7
2.yum安装PostgreSQL

#先安装PostgreSQL的yum源
yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

#安装PostgreSQL
yum install -y postgresql14-server

#初始化,此条命令可直接执行,因为yum在安装postgresql14-server的时候,就已经将postgresql-14-setup放到了/usr/bin下
postgresql-14-setup initdb

#设置开机启动
systemctl enable postgresql-14

#修改配置文件
cd /var/lib/pgsql/14/data/
vim postgresql.conf
	listen_addresses = '*'	# 可远程连接
vim pg_hba.conf
	host    all     all             0.0.0.0/0                 scram-sha-256		#在文件末尾加入这一行

#启动
systemctl start postgresql-14	

2.基础客户端命令使用

以下命令均是在shell环境下(-bash-4.2$)输入的

# postgres用户是安装时自动创建的,用postgresql自带客户端需要切换到这个用户下
su - postgres

psql		# 输入psql即可进入交互式客户端

psql --version		# 查看版本

以下命令是在客户端交互环境下输入的

#查看所有数据库,相当于show databases(l可以记为list)
postgres=# \l
                                  List of databases
   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-----------+----------+----------+-------------+-------------+-----------------------
 db1       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 db2       | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 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
(5 rows)

#切换数据库,相当于use db1(c可记为connect)
postgres=# \c db1;
You are now connected to database "db1" as user "postgres".

#查看当前库下所有表(d记为dir,t记为table)
db1=# \dt;
        List of relations
 Schema | Name | Type  |  Owner   
--------+------+-------+----------
 public | user | table | postgres
(1 row)

#查看某表表结构
db1=# \d user;
                       Table "public.user"
 Column |          Type          | Collation | Nullable | Default 
--------+------------------------+-----------+----------+---------
 id     | integer                |           | not null | 
 name   | character varying(255) |           | not null | 
Indexes:
    "user_pkey" PRIMARY KEY, btree (id)
    "id_index" UNIQUE, btree (id)

#新建库(末尾分号一定不能省略,省略后回车不会报错,但命令也不会执行)
db1=# create database db3;
CREATE DATABASE

# 删除库
db1=# drop database db3;
DROP DATABASE

#新增用户
db1=# create user li with login password '123456';
CREATE ROLE

3.备份恢复

#备份
pg_dump -h127.0.0.1 -Upostgres db1 >/root/db1_postgres.sql

#恢复
psql -h127.0.0.1 -Upostgres db1 </root/db1_postgres.sql

3.增删改查

#查询
db1=# SELECT * FROM "user" WHERE "id"=1;
 id | name 
----+------
  1 | chen
(1 row)

#插入
db1=# INSERT INTO "user" VALUES(4,'dong');
INSERT 0 1

#更新
db1=# UPDATE "user" SET "name"='penglu' WHERE "id"=4;
UPDATE 1

#删除
db1=# DELETE FROM "user" WHERE "id"=4;
DELETE 1

你可能感兴趣的:(postgresql,数据库,postgresql,数据库)