世界上最先进的开源关系型数据库 ——PostgreSql 常用命令
用户操作命令
登录
1、指定参数登录
shell
1 | psql -U username -d database_name -h host -W |
参数含义:
-U
指定用户-d
要连接的数据库-h
要连接的主机-W
提示输入密码。
2、使用 postgres
同名用户后登录
shell
1 | su username |
注意:
当不指定参数时
psql
使用操作系统当前用户的用户名作为 postgres 的登录用户名和要连接的数据库名。所以在 PostgreSQL 安装完成后可以通过以上方式登录。
修改密码
shell
1 | su - postgres |
创建用户
1、系统命令行创建
shell
1 | createuser username |
2、PostgresSQL 命令行创建(使用 CREATE ROLE)
shell
1 | CREATE ROLE rolename; |
3、PostgresSQL 命令行创建(使用 CREATE USER)
shell
1 | CREATE USER testuser WITH PASSWORD 'testuser'; |
CREATE USER
和CREATE ROLE
的区别在于,CREATE USER
指令创建的用户默认是有登录权限的,而CREATE ROLE
没有。
允许远程访问
在 pg_hba.conf
添加以下命令,配置用户的访问权限:
plaintext
1 | # TYPE DATABASE USER ADDRESS METHOD |
在 postgresql.conf
添加以下命令:
plaintext
1 | listen_addresses = '*' |
数据库操作命令
创建数据库
shell
1 | CREATE DATABASE testuser_1 OWNER testuser; |
切换数据库
相当于 mysql 的 use dbname
shell
1 | \c dbname |
列举数据库
相当于 mysql 的 show databases
shell
1 | \l |
删除数据库
shell
1 | drop database [数据库名]; |
列举表
相当于 mysql 的 show tables
shell
1 | \dt |
查看表结构
相当于 desc tblname,show columns from tbname
plaintext
1 | \d tblname |
查看索引
shell
1 | \di |
表操作命令
重命名一个表
shell
1 | alter table [表名A] rename to [表名B]; |
删除一个表
shell
1 | drop table [表名]; |
在已有的表里添加字段
shell
1 | alter table [表名] add column [字段名] [类型]; |
删除表中的字段
shell
1 | alter table [表名] drop column [字段名]; |
重命名一个字段
shell
1 | alter table [表名] rename column [字段名A] to [字段名B]; |
给一个字段设置缺省值
shell
1 | alter table [表名] alter column [字段名] set default [新的默认值]; |
去除缺省值
shell
1 | alter table [表名] alter column [字段名] drop default; |
在表中插入数据
shell
1 | insert into 表名 ([字段名m],[字段名n],......) values ([列m的值],[列n的值],......); |
修改表中的某行某列的数据
shell
1 | update [表名] set [目标字段名]=[目标值] where [该行特征]; |
删除表中某行数据
shell
1 | delete from [表名] where [该行特征]; |
创建表
shell
1 | create table ([字段名1] [类型1] ;,[字段名2] [类型2],......<,primary key (字段名m,字段名n,...)>;); |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 枫叶!