PostgreSQL入门

Stella981
• 阅读 585

PostgreSQL入门-安装与基本使用(Ubuntu)

PostgreSQL 是一个免费的对象-关系数据库服务器(ORDBMS),号称是 "世界上最先进的开源关系型数据库"。

PostgreSQL 是以加州大学计算机系开发的 POSTGRES 4.2版本为基础的对象关系型数据库。

今天在Ubuntu系统上,我们一起来安装并简单使用一下PostgreSQL数据库。

1.查看当前系统版本:

$ cat /etc/issue
Ubuntu 16.04.6 LTS \n \l

$ sudo lsb_release -a
LSB Version:    
core-9.20160110
ubuntu0.2-amd64:core-9.20160110
ubuntu0.2-noarch:security-9.20160110
ubuntu0.2-amd64:security-9.20160110
ubuntu0.2-noarch
Distributor ID:    Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:    xenial

系统是 Ubuntu 16.04.6 LTS。

2.安装 PostgreSQL

$ sudo apt-get install postgresql

执行实例如下:

$ sudo apt-get install postgresql
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libpq5 
  postgresql-9.5 
  postgresql-client-9.5 
  postgresql-client-common 
  postgresql-common 
  postgresql-contrib-9.5 
  ssl-cert
 … …
Creating config file /etc/postgresql-common/createcluster.conf with new version
Creating config file /etc/logrotate.d/postgresql-common with new version
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
Removing obsolete dictionary files:
Setting up postgresql-9.5 (9.5.19-0ubuntu0.16.04.1) ...
Creating new cluster 9.5/main ...
  config /etc/postgresql/9.5/main
  data   /var/lib/postgresql/9.5/main
  locale en_US.UTF-8
  socket /var/run/postgresql
  port   5432
update-alternatives: using /usr/share/postgresql/9.5/man/man1/postmaster.1.gz to provide /usr/share/man/man1/postmaster.1.gz (postmaster.1.gz) in auto mode
Setting up postgresql (9.5+173ubuntu0.2) ...
Setting up postgresql-contrib-9.5 (9.5.19-0ubuntu0.16.04.1) ...
Processing triggers for libc-bin (2.23-0ubuntu11) ...
Processing triggers for ureadahead (0.100.0-19.1) ...
Processing triggers for systemd (229-4ubuntu21.21) ...

默认已经安装了 postgresql 的服务器(postgresql-9.5)和客户端(postgresql-client-9.5)。

2019年10月03日,已经发布了PostgreSQL 12,如果想安装最新版的,需要更新一下源,参加 PostgreSQL Apt Repository

可以使用 psql --version 来查看当前安装的版本:

$ psql --version
psql (PostgreSQL) 9.5.19

安装后会默认生成一个名为 postgres的数据库和一个名为postgres的数据库用户。

同时还生成了一个名为 postgres 的 Linux 系统用户。

可以使用以下命令查看:

#查看用户
$ cat /etc/passwd

#查看用户组  
$ cat /etc/group

3.使用PostgreSQL控制台修改 postgres 数据库用户密码

默认生成的 postgres 的数据库用户没有密码,现在我们使用 postgres Linux用户的身份来登录到管理控制台中。

# 切换到postgres用户。
$ sudo su - postgres
postgres@iZm5e8p54dk31rre6t96xuZ:~$ 
postgres@iZm5e8p54dk31rre6t96xuZ:~$ whoami
postgres

Linux 用户 postgres 以同名的 postgres 数据库用户的身份登录,不用输入密码的。

postgres@iZm5e8p54dk31rre6t96xuZ:~$ psql
psql (9.5.19)
Type "help" for help.

postgres=#

使用 \password 命令,为 postgres 用户设置一个密码

postgres=# 
postgres=# CREATE USER db_user WITH PASSWORD 'PWD123456';
CREATE ROLE
postgres=# 

创建用户数据库,这里为testdb,并指定所有者为db_user。

postgres=# CREATE DATABASE testdb OWNER db_user;
CREATE DATABASE
postgres=# 

将 testdb 数据库的所有权限都赋予 db_user 数据库用户, 否则 db_user 只能登录控制台,没有数据库操作权限。

postgres=# GRANT ALL PRIVILEGES ON DATABASE testdb TO db_user;
GRANT

使用 \du 查看当前的数据库用户:

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

最后,使用 \q 命令退出控制台, 并使用 exit 命令退出当前 db_user Linux用户。

postgres=# \q
postgres@iZm5e8p54dk31rre6t96xuZ:~$ 
postgres@iZm5e8p54dk31rre6t96xuZ:~$ exit
logout

4.数据库基本操作实例

创建数据库与删除数据库:

# 创建数据库
postgres=# CREATE DATABASE lusiadas;
CREATE DATABASE

# 删除数据库
postgres=# DROP DATABASE lusiadas;
DROP DATABASE

使用 \c 切换数据库:

postgres=# CREATE DATABASE testdb;
CREATE DATABASE

postgres=# \c testdb;
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
You are now connected to database "testdb" as user "postgres".

新建表与删除表:

# 创建一个表 tb_test:(两个字段,其中id 为自增ID)
testdb=> CREATE TABLE tb_test(id bigserial, name VARCHAR(20));
CREATE TABLE
# 删除一个表 tb_test
testdb=> DROP table tb_test;
DROP TABLE

增删改查操作:

# 创建一个用户表 tb_users(三个字段,其中id 为自增ID)
testdb=> CREATE TABLE tb_users(id bigserial, age INT DEFAULT 0, name VARCHAR(20));
CREATE TABLE
 
# 使用 INSERT 语句插入数据 
testdb=> INSERT INTO tb_users(name, age) VALUES('张三丰', 212);
INSERT 0 1
testdb=> INSERT INTO tb_users(name, age) VALUES('李四光', 83);
INSERT 0 1
testdb=> INSERT INTO tb_users(name, age) VALUES('王重阳', 58);
INSERT 0 1

# 查询数据
testdb=> select * from tb_users;
 id | age |  name  
----+-----+--------
  1 | 212 | 张三丰
  2 |  83 | 李四光
  3 |  58 | 王重阳
(3 rows)
testdb=> select * from tb_users WHERE id=3;
 id | age |  name  
----+-----+--------
  3 |  58 | 王重阳
(1 row)

# 更新数据 (执行后输出更新的条数,第二次执行失败所以输出为`UPDATE 0`)
testdb=> UPDATE tb_users set name = '全真派王重阳' WHERE name = '王重阳';
UPDATE 1
testdb=> UPDATE tb_users set name = '全真派王重阳' WHERE name = '王重阳';
UPDATE 0

# 插入2条数据
testdb=> INSERT INTO tb_users(name, age) VALUES('赵四', 0);
INSERT 0 1
testdb=> INSERT INTO tb_users(name, age) VALUES('赵五娘', 0);
INSERT 0 1

# 模糊查询
testdb=> SELECT * FROM tb_users WHERE name LIKE '赵%';
 id | age |  name  
----+-----+--------
  4 |   0 | 赵五娘
  5 |   0 | 赵四
(2 rows)

# 修改表结构: 新增字段 
testdb=# ALTER TABLE tb_users ADD email VARCHAR(50);
ALTER TABLE

# 修改表结构: 修改字段 
testdb=# ALTER TABLE tb_users ALTER COLUMN email TYPE VARCHAR(100);
ALTER TABLE

# 删除字段
testdb=# ALTER TABLE tb_users DROP COLUMN email;
ALTER TABLE

# 删除记录
testdb=> DELETE FROM tb_users WHERE id = 5;
DELETE 1

使用 pg_database_size() 查看数据库的大小:

testdb=# select pg_database_size('testdb');
 pg_database_size 
------------------
          7991967
(1 row)
testdb=# select pg_size_pretty(pg_database_size('testdb'));
 pg_size_pretty 
----------------
 7805 kB
(1 row)

5.PostgreSQL 的 timestamp 类型

查询 current_timestamp

testdb=# select current_timestamp;
       current_timestamp       
-------------------------------
 2019-11-11 08:33:35.369887+00
(1 row)

使用 current_timestamp(0) 定义时间类型精度为0:(有时区)

testdb=# select current_timestamp(0);
   current_timestamp    
------------------------
 2019-11-11 08:31:08+00
(1 row)

使用 current_timestamp(0) 定义时间类型精度为0:(去掉时区)

testdb=# select current_timestamp(0)::timestamp without time zone;
  current_timestamp  
---------------------
 2019-11-11 08:31:20
(1 row)

testdb=# select cast (current_timestamp(0) as  timestamp without time zone);
  current_timestamp  
---------------------
 2019-11-11 08:32:26
(1 row)

时间戳:

testdb=# select extract(epoch from now());
    date_part     
------------------
 1573461495.47821
(1 row)

设置数据库时区:

视图 pg_timezone_names 保存了所有可供选择的时区:

# 查看时区  
select * from pg_timezone_names;  

比如可以选择上海 Asia/Shanghai 或重庆 Asia/Chongqing, 最简单的直接 PRC:

testdb=# set time zone 'PRC'; 
SET
testdb=# show time zone;
 TimeZone 
----------
 PRC
(1 row)
testdb=# SELECT LOCALTIMESTAMP(0);
   localtimestamp    
---------------------
 2019-11-11 16:42:54
(1 row)

Reference

https://www.postgresql.org/docs/8.4/sql-altertable.html
http://www.ruanyifeng.com/blog/2013/12/getting_started_with_postgresql.html

[END]

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
九路 九路
1年前
PostgreSQL 数组类型使用详解
PostgreSQL数组类型使用详解可能大家对PostgreSQL这个关系型数据库不太熟悉,因为大部分人最熟悉的,公司用的最多的是MySQL我们先对PostgreSQL数据库(下面简称PG)简单的介绍一下,以后有机会,再
待兔 待兔
3年前
PostgreSQL介绍以及如何开发框架中使用PostgreSQL数据库
最近准备下PostgreSQL数据库开发的相关知识,本文把总结的PPT内容通过博客记录分享,本随笔的主要内容是介绍PostgreSQL数据库的基础信息,以及如何在我们的开发框架中使用PostgreSQL数据库,希望大家多多提意见。1、PostgreSQL数据库介绍PostgreSQL是以加州大学伯克利分校计算机系开发的POSTGRES,现在已经更
御弟哥哥 御弟哥哥
3年前
PostgreSQL简史
现在被称为PostgreSQL的对象关系型数据库管理系统是从加州大学伯克利分校写的POSTGRES软件包发展而来的。经过二十多年的发展,PostgreSQL是世界上可以获得的最先进的开源数据库。2.1.伯克利的POSTGRES项目由MichaelStonebraker教授领导的POSTGRES项目是由防务高级研究项目局(DARPA)、陆军研究办公室(A
待兔 待兔
3年前
阿里云德哥:PostgreSQL 数据库的前世今生
内容摘要PostgreSQL是以加州大学伯克利分校计算机系开发的Posrgres,现在已经更名为PostgreSQL。它是一个自由的对象关系数据库服务器(数据库管理系统),它在灵活的BSD风格许可证下发行。PostgreSQL中国社区发起人之一Digoal为我们带来PostgreSQL前世今生、社区理念以及阿里云Postgr
Wesley13 Wesley13
2年前
Ubuntu安装PostgreSQL 10
一、介绍对象关系型数据库,支持各种OS默认端口:5432Download:https://www.postgresql.org/download/(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.postgresql.org%2Fdownload
Stella981 Stella981
2年前
PostgreSQL 学习一 安装和入门
自从MySQL被Oracle收购以后,PostgreSQL逐渐成为开源关系型数据库的首选。  本文介绍PostgreSQL的安装和基本用法,供初次使用者上手。以下内容基于Debian操作系统,其他操作系统实在没有精力兼顾,但是大部分内容应该普遍适用。   !640x220(http://static.oschina.net/uploads/
Stella981 Stella981
2年前
PostgreSQL知识树
!(https://static.oschina.net/uploads/space/2018/0527/193437_yJLv_233784.png)PostgreSQL使用并学习了78年了,最近在梳理PostgreSQL相关知识树,个人认为数据库由关系型存储关系以及事务两大基石构成的。其次为了易用性添加了通用工具以及管理功能。在此将数据库分
Stella981 Stella981
2年前
Postgresql部署及简单操作
PostgreSQL是一个功能强大的开源对象关系数据库管理系统(ORDBMS),在开源数据库使用上与MySQL各领风骚。但也有不少人质疑postgresql的未来,正所谓,赞扬或批判一种数据库都必须先了解它,然后才可有话语权。为了更多的了解postgresql,我们就先部署一套实例作为了解它的基础。!(https://oscimg.oschina
3A网络 3A网络
1年前
PostgreSQL 数组类型使用详解
PostgreSQL数组类型使用详解PostgreSQL数组类型使用详解可能大家对PostgreSQL这个关系型数据库不太熟悉,因为大部分人最熟悉的,公司用的最多的是MySQL我们先对PostgreSQL数据库(下