PostgreSQL入门简介

一、PostgreSQL数据库安装

1)yum安装

* 安装存储库
    yum install https://download.postgresql.org/pub/repos/yum/10/redhat/rhel-7-x86_64/pgdg-centos10-10-1.noarch.rpm

* 安装客户端
    # yum install postgresql

* 安装服务端
    # yum install postgresql-server

* 安装拓展包
    # yum install postgresql-devel.x86_64 

* 安装附加模块
    # yum install postgresql-contrib.x86_64 

2)验证postgresql安装

# rpm -qa | grep postgresql
postgresql-libs-9.2.23-3.el7_4.x86_64
postgresql-9.2.23-3.el7_4.x86_64
postgresql-server-9.2.23-3.el7_4.x86_64

3)配置数据库

* 初始化数据库
    # /usr/bin/postgresql-setup initdb

* 启动postgresql服务
    # systemctl start postgresql

* 设置开机自启动
    # systemctl enable postgresql

* 登录postgresql
    # su - postgres
    $ psql -U postgres

* 修改postgres用户密码
    ALTER USER postgres with encrypted password 'postgres';

4)远程配置

* 开启远程访问
    # vi /var/lib/pgsql/data/postgresql.conf 
        listen_addresses = '*'          # what IP address(es) to listen on;

* 信任远程连接
    # vi /var/lib/pgsql/data/pg_hba.conf 
        # IPv4 local connections:
        host    all             all             127.0.0.1/32            trust
        host    all             all             192.168.9.139/32        trust

* 重启postgresql服务
    # systemctl restart postgresql

5)psql连接

* 连接命令
    # psql -d postgres -h 192.168.9.139 -p 5432 -U postgres

6)用户管理

* 创建用户
    CREATE USER admin WITH PASSWORD '123456';

* 修改密码
    ALTER USER admin with encrypted password 'admin';

* 连接验证
    # psql -d postgres -h 192.168.9.139 -p 5432 -U admin

二、数据库操作

1)创建数据库

* 普通创建
    CREATE DATABASE pgdb;

* 创建指定用户数据库
    CREATE DATABASE pgadmindb OWNER admin;  
    GRANT ALL PRIVILEGES ON DATABASE pgadmindb TO admin;

2)删除数据库

* 普通删除
    DROP DATABASE pgdb;

* 判断数据库存在后再删除
    DROP DATABASE IF EXISTS pgdb;

3)其它操作

* 切换数据库
    \c pgdb;

* 退出数据库
    \q

三、数据表操作

1)创建表

CREATE TABLE numerical (
  "a" int4,
  "b" int4
);

2)删除表

DROP TABLE IF EXISTS numerical;

3)加载数据

INSERT INTO numerical (SELECT i, i + 1 FROM generate_series(1, 10000) AS i);

4)清空数据表

truncate table numerical;

5)查询

* 统计查询
SELECT COUNT(1) FROM numerical;

* 累计查询
SELECT SUM(a) FROM numerical;

* 平均查询
SELECT SUM(a)/COUNT(1) FROM numerical;

猜你喜欢

转载自blog.csdn.net/volitationLong/article/details/81669745