1. 程式人生 > 資料庫 >PostgreSQL使用者、資料庫及表的管理、操作與授權方式

PostgreSQL使用者、資料庫及表的管理、操作與授權方式

摘要

PostgreSQL的常用命令

1、登入資料庫

/* 切換到資料庫使用者 */
su - postgres
/* 登入 */
psql

登入成功顯示如下:

bash-4.2$ psql
psql (9.3.17)
Type "help" for help.
postgres=> 

2、切換資料庫

/* 登入指定資料庫 */
psql -U user -d dbname
/* 列舉資料庫 */
\l
/* 切換資料庫 */
\c dbname

3、使用者管理

/* 建立使用者 */
CREATE ROLE rolename;
CREATE USER username WITH PASSWORD '*****';
/* 顯示所有使用者 */
\du
/* 修改使用者許可權 */
ALTER ROLE username WITH privileges;
/* 賦給使用者表的所有許可權 */
GRANT ALL ON tablename TO user; 
/* 賦給使用者資料庫的所有許可權 */
GRANT ALL PRIVILEGES ON DATABASE dbname TO dbuser;
/* 撤銷使用者許可權 */
REVOKE privileges ON tablename FROM user;
/* 撤銷使用者許可權 */

4、資料庫操作

/* 建立資料庫 */
create database dbname; 
/* 刪除資料庫 */
drop database dbname; 

5、表操作

/* 增加讓主鍵自增的許可權 */
grant all on sequence tablename_keyname_seq to webuser;
 /* 重新命名一個表 */
alter table [表名A] rename to [表名B]; 
/* 刪除一個表 */
drop table [表名]; 
/* 在已有的表裡新增欄位 */
alter table [表名] add column [欄位名] [型別]; 
/* 刪除表中的欄位 */
alter table [表名] drop column [欄位名]; 
/* 重新命名一個欄位 */
alter table [表名] rename column [欄位名A] to [欄位名B]; 
/* 給一個欄位設定預設值 */
alter table [表名] alter column [欄位名] set default [新的預設值];
/* 去除預設值 */
alter table [表名] alter column [欄位名] drop default; 
/* 插入資料 */
insert into 表名 ([欄位名m],[欄位名n],......) values ([列m的值],[列n的值],......); 
/* 修改資料 */
update [表名] set [目標欄位名]=[目標值] where ...; 
/* 刪除資料 */
delete from [表名] where ...; 
/* 刪除表 */
delete from [表名];
/* 查詢 */
SELECT * FROM dbname WHERE ...;
/* 建立表 */
create table (
  [欄位名1] [型別1] primary key,[欄位名2] [型別2],......,[欄位名n] [欄位名n] )

6、退出

\q
quit

補充:postgresql 授權某個資料庫的許可權給test 賬號 使該賬號 只能操作指定DB 不能操作其他DB

alter user test set default_transaction_read_only=on;
grant all on database crm_db to test;
grant select on all tables in schema public to test;   // 起作用的是這句 要進入crm_db 操作,在那個db環境執行就授哪個db的權

刪除前撤銷

revoke all on database crm_prod_myl from test;
revoke select on all tables in schema public from test;

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。