PostgreSQL的使用

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

本文介绍PostgreSQL的基本用法

sql

create user test_user with password '123456';

sql

drop user test_user;

sql

create tablespace test_tab owner test_user location '/data/pgsql/tablespaces/test_tab';

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

bash

mkdir /data/pgsql/data/test_tab

sql

grant create on tablespace test_tab to test_user2;

sql

alter table test_tab set tablespace test_tab2;

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

sql

drop tablespace test_tab;
drop tablespace if exists test_tab;

sql

create database test_db;
create database test_db tablespace test_user;
create database test_db with owner test_user tablespace test_tab;

text

drop database "test_db";

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

sql

alter database "test_db" set tablespace test_tab2

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

sql

create schema test_schema;

sql

drop schema test_schema;

sql

grant all on database "test_db" to test_user;

sql

grant all on all tables in schema test_schema to test_user;

sql

DROP DATABASE test_db;

可能会提示:

sql

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

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

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

sql

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。

相关内容