postgres基本操作大全


首先切換到postgres用戶

su - postgres -- 首先切換到postgres

常識:PG安裝完后默認帶有postgres庫,可以先進入postgres庫再去創建新庫

1創建用戶:

postgres=# create user  testuser  with  password '123456';

CREATE ROLE

2創建數據庫:

postgres=# create database  testdb  owner  testuser;     創建數據庫給指定用戶

3將數據庫的權限全部賦給用戶:

postgres=# grant all  on database  testdb  to testuser;

4創建schema:

postgres=# create schema  abc  authorization abcuser;

create schema

postgres=# create schema authorization abcuser; 指定了owner則schema名字和owner一致

5刪除schema  

drop  schema  abc  cascade;     加了cascade可以把關聯的表和視圖一起刪掉

6 修改數據庫密碼

alter user abcuser with password '123' 

7導入整個數據庫:

\q先退出數據庫編輯模式

psql -U testuser   testdb <  /data/backup.sql    用戶名和數據庫

8遠程連接和導入命令:

psql  -h  主機域名或者IP   -p  端口  -U 用戶  -d  數據庫     (PG默認端口5432)

例如:psql  -h postgres.db.com   -p 5432  -U testuser  -d  testdb

psql  -h postgres.db.com   -p 5432  -U testuser  -d  testdb  <  table_create.utf8.sql

9切換數據庫

\c dbname  (相當於mysql 的  use dbname)

10列舉數據庫

\l (相當於mysql 的show databases)

11列舉表

\dt (相當於mysql 的show tables)

12查看表結構

\d tblname (相當於mysql 的 desc  tblname   ,   show columns from tbname)

13查看索引

\di

 

表操作:

1改變表名

alter   table  [表名A]   rename  to [表名B];

2刪除表

drop table  [表名];

3表里添加字段

alter  table [表名]  add column  [字段] [類型];

4刪除表字段

alter table  [表名]  drop column [字段];

5重命名一個表字段

alter  table [表名]   rename column [A] to [B];

6表中插入數據

insert  into 表名 (字段名m) values (列m的值)

7更新表中某行某列的數據

update  [表名]  set  [目標字段名]=[目標值] where [改行特征];

8刪除表中某行數據

delete  from 表名 where [改行特征];

9刪除整個表

delete from  表名;

10創建表

create table  字段名  類型;

 

角色創建:

1create  role  rolename  with optional_permisson;

2create  role  rolename with login;

\h  create role 可查看創建角色時可設置的管理權限

3改變角色的權限“

alter  role rolename with attribute_options;

alter  role rolename with nologin;

4賦予角色權限

grant permission_type on  tablename  to rolename;

 

備注:

\copyright  顯示PG的使用和發行條款

\encoding  [字元編碼名稱]

\password  [username]

\q 退出

create role  rolename 和 create user username這兩者的區別:創建的角色rolename沒有登錄權限,而創建的用戶username是有登錄權限的,

\du顯示用戶和用戶的屬性

pg_ctl reload重啟PG

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM