PostgreSQL的使用

警告
本文最后更新于 2022-11-01,文中内容可能已过时。

本文介绍PostgreSQL的基本用法

1
create user test_user with password '123456';
1
drop user test_user;
1
create tablespace test_tab owner test_user location '/data/pgsql/tablespaces/test_tab';

如果目录不存在会提示:ERROR: directory "/data/pgsql/data/test_tab" does not exist 创建目录,需要注意权限

1
mkdir /data/pgsql/data/test_tab
1
grant create on tablespace test_tab to test_user2;
1
alter table test_tab set tablespace test_tab2;

删除表空间前必须要删除该表空间下的所有数据库对象,否则无法删除。

1
2
drop tablespace test_tab;
drop tablespace if exists test_tab;
1
2
3
create database test_db;
create database test_db tablespace test_user;
create database test_db with owner test_user tablespace test_tab;
1
drop database "test_db";

执行该操作;必须是没有人连着对应的数据库

1
alter database "test_db" set tablespace test_tab2

注意1:执行该操作;不能连着对应数据库操作 注意2:执行该操作;对应的数据库不能存在表或者索引已经指定默认的表空间 注意3:执行该操作;必须是没有人连着对应的数据库

1
create schema test_schema;
1
drop schema test_schema;
1
grant all on database "test_db" to test_user;
1
grant all on all tables in schema test_schema to test_user;
1
DROP DATABASE test_db;

可能会提示:

1
2
ERROR:  database "test_db" is being accessed by other users
DETAIL:  There are 3 other sessions using the database.

删除数据库失败,因为这里还有3个链接连接到该数据库上,PostgreSQL在有进程连接到数据库时,对应的数据库是不允许被删除的。

执行以下语句,再执行DROP操作,就可以删除数据库了。

1
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname='test_db' AND pid<>pg_backend_pid();

上面语句说明:

pg_terminate_backend:用来终止与数据库的连接的进程id的函数。

pg_stat_activity:是一个系统表,用于存储服务进程的属性和状态。

pg_backend_pid():是一个系统函数,获取附加到当前会话的服务器进程的ID。

相关内容