PostgreSQL数据库,也叫PG数据库,默认使用create命令,创建user(管理员)和db(数据库)。先以PG数据库的默认账户postgres登录PG,然后再创建管理员与数据库。
这里以PostgreSQL v14创建数据库hellodb,以及对应的管理员hello为例,系统是Mac,进行说明。
1、设置psql环境
将如下语句,添加到~/.zhsrc文件里,如图(1)所示。
export PATH=/Library/PostgreSQL/14/bin:$PATH
![](https://img-blog.csdnimg.cn/a3e72cdeb4a244be8936c0b6d1138517.png)
2、登录PG
psql -U postgres -d postgres
3、创建数据库和管理员
3.1 创建管理员
## 添加一个用户hello,并设置密码
create user hello with password '新的密码';
3.2 创建数据库
## 给hello用户,创建一个数据库叫hellodb
create database hellodb owner hello;
3.3 授予hello当前DB的全部权限
以下4步是一个整体,不要跳着执行,否则会出现"明明给A授权的,却发现是给B授予"。
## 1) 先退出postgre数据库
\q
## 2) 登录hellodb数据库
psql -U postgres -d hellodb
## 3) 将hellodb的所有权限赋予hello
grant all privileges on database hellodb to hello;
## 4) 授予hello对hellodb数据库的读写权限
grant usage on schema public to hello;
grant all privileges on all tables in schema public to hello;
grant all privileges on all sequences in schema public to hello;
grant select,insert,update,delete on all tables in schema public to hello;
grant all on schema public to hello;
3.4 授予hello创建新数据库的权限
## 给hello用户添加创建数据库的属性
alter role hello createdb;
如图(2) 、图(3)所示:
![](https://img-blog.csdnimg.cn/c96b9bc6c1004553a7b60df9a8d78791.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAc2FucWltYQ==,size_17,color_FFFFFF,t_70,g_se,x_16)
![](https://img-blog.csdnimg.cn/a959130bf4b44af49b97e1f9b20abdc2.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAc2FucWltYQ==,size_20,color_FFFFFF,t_70,g_se,x_16)
附录
hello用户,登录hellodb数据库
psql -U hello -d hellodb