psql 命令总结

 

1 登录数据库

Connection options:
-h, --host=HOSTNAME database server host or socket directory (default: "/var/run/postgresql")
-p, --port=PORT database server port (default: "5432")
-U, --username=USERNAME database user name (default: "zhangjin")
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)

$ psql -h 127.0.1 -U postgres -p 5432 -W

Password for user postgres: 
psql (9.3.11)
SSL connection (cipher: DHE-RSA-AES256-GCM-SHA384, bits: 256)
Type "help" for help.

postgres=#

-d 可直接登录到database 如

$ psql -h 127.0.1 -U postgres -p 5432 -d mytestdb -W

也可以设置环境变量

export PGDATABASE=testdb
export PGHOST=127.0.0.1
export PGPORT=5432
export PGUSER=postgres

或.pgpass 在/home/postgres目录下 

 

2 常用命令

 psql 命令都是以 \ 作为开始 ,

 \l 查看数据库

postgres=# \l
                                  List of databases
    Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
------------+----------+----------+-------------+-------------+-----------------------
 basedb     | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 |
 postgres   | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | 
 root       | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 |
 template0  | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres          +
            |          |          |             |             | postgres=CTc/postgres
 template1  | postgres | UTF8     | zh_CN.UTF-8 | zh_CN.UTF-8 | =c/postgres          +
            |          |          |             |             | postgres=CTc/postgres
(5 rows)

\c 连接到database

postgres=# \c postgres
You are now connected to database "postgres" as user "postgres".

\d 列出当前数据库的所有表

poi=# \d
                  List of relations
 Schema |          Name           | Type  |  Owner   
--------+-------------------------+-------+----------
 public | my_table | table | postgres
(1 row)

\d tablename 列出指定表 , 可加通配符 * ?

\dt 只显示匹配的表

\di 只显示索引

\ds 只显示序列

\dv 只显示视图

\df 显示函数

\dn 所用的schema

\db 所用的表空间

\dx 查看扩展 extension

\dg \du 列出所有角色或用户 

\dp \z 显示表的权限分配情况

\q  退出

3 其他设置命令

\timing 显示sql以执行时间

\encoding gbk; \encoding utf8 指定客户端的字符编码

\x 把表中的每一行的每列数据都拆分为单行展示

4 执行存储在外部文件中的SQL命令

\i 或 在sql命令行加 -f<filename>

5 自动提交

postgres=# begin;
BEGIN
postgres=# alter database poi rename to poi1;
ALTER DATABASE
postgres=# commit;
COMMIT

或 

\set AUTOCOMMIT off 注意大写

6 查看正在连接的客户端

select * from pg_stat_activity ;

借助 \x显示

 $ kill -9 pid

 

posted @ 2016-04-13 13:19  Eamon13  阅读(1066)  评论(1编辑  收藏  举报