上篇文章介绍了如何安装PostgreSQL,这篇介绍一些简单命令:
上篇链接:http://blog.csdn.net/badly9/article/details/48544459
1.psql命令简介:
首先登入PostgreSQL控制台:
[pg@edb1 ~]$ psql postgres
psql (9.3.9)
Type "help" for help.
postgres=#
查看帮助:
postgres=# \h
Available help:
ABORT CLUSTER DEALLOCATE END
ALTER AGGREGATE COMMENT DECLARE EXECUTE
ALTER COLLATION COMMIT DELETE EXPLAIN
.....
这里会列出所有能执行的命令:
如果需要某个命令具体的帮助还可以使用:
postgres=# \h create user
Command: CREATE USER
Description: define a new database role
Syntax:
CREATE USER name [ [ WITH ] option [ ... ] ]
where option can be:
SUPERUSER | NOSUPERUSER
| CREATEDB | NOCREATEDB
| CREATEROLE | NOCREATEROLE
| CREATEUSER | NOCREATEUSER
| INHERIT | NOINHERIT
| LOGIN | NOLOGIN
| REPLICATION | NOREPLICATION
| CONNECTION LIMIT connlimit
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| VALID UNTIL 'timestamp'
| IN ROLE role_name [, ...]
| IN GROUP role_name [, ...]
| ROLE role_name [, ...]
| ADMIN role_name [, ...]
| USER role_name [, ...]
| SYSID uid
2.创建用户及数据库:
(1)PostgreSQL控制台创建
创建用户:
postgres=# create user badly9 encrypted password 'badly9';
CREATE ROLE
创建数据库
postgres=# create database badly9db;
CREATE DATABASE
授予权限
postgres=# grant all on database badly9db to badly9;
GRANT
(2)命令行创建
创建用户:
[pg@edb1 ~]$ createuser --help --可以用来查看help,输出太多就不贴了
[pg@edb1 ~]$ createuser -W -E badly9
Password:
创建属于badly9的数据库badly9db:
[pg@edb1 ~]$ createdb -O badly9 badly9db
3.使用badly9用户登录badly9db:
[pg@edb1 ~]$ psql -d badly9db -h 127.0.0.1 -p 5432 -U badly9 -W
Password for user badly9:
psql (9.3.9)
Type "help" for help.
badly9db=>
上边登陆的含义是使用用户badly9登陆ip地址为127.0.0.1监听端口为5432的数据库badly9db
4.简单的DDL、DML及查询测试:
(1)DDL测试:
badly9db=> create table badly9(x int);
CREATE TABLE
badly9db=> alter table badly9 add y int;
ALTER TABLE
badly9db=> alter table badly9 drop column y;
ALTER TABLE
badly9db=> alter table badly9 rename to badly10;
ALTER TABLE
badly9db=> drop table badly10;
DROP TABLE
(2)DML及查询测试
badly9db=> create table badly9(x varchar(20));
CREATE TABLE
badly9db=> insert into badly9 values('who');
INSERT 0 1
badly9db=> select * from badly9;
x
-----
who
(1 row)
badly9db=> update badly9 set x='badly' where x='who';
UPDATE 1
badly9db=> select * from badly9;
x
-------
badly
(1 row)
badly9db=> delete from badly9 where x='badly';
DELETE 1
badly9db=> select * from badly9;
x
---
(0 rows)
5.退出数据库
badly9=# \q
6.删除数据库
(1)PostgreSQL控制台
[pg@edb1 ~]$ psql postgres
psql (9.3.9)
Type "help" for help.
postgres=# drop database badly9db;
DROP DATABASE
(2)命令行
[pg@edb1 ~]$ dropdb badly9db
7.删除用户
(1)PostgreSQL控制台
[pg@edb1 ~]$ psql postgres
psql (9.3.9)
Type "help" for help.
postgres=# drop user badly9;
DROP ROLE
(2)命令行
[pg@edb1 ~]$ dropuser badly9
注意:删除用户之前要先删除属于它的数据库,否则会报错。