您的位置:首页 > 数据库

PostgreSQL学习第八篇--psql的使用技巧和注意事项

2016-11-28 14:42 525 查看
1.历史命令与补全功能
可以使用上下键把以前使用过的命令或SQL语句调出来。
连续按两个tab键表示命令补全或者提示输入。--类似于Linux功能

2.自动提交方面的技巧
在psql中,事务是自动提交的。(与oracle不同)
如果不想自动提交,可以:
默认,postgresql是自动提交的,可以避免自动提交
1)使用begin;命令
示例:
postgres=# begin;
BEGIN
postgres=# insert into test values(2,2);
INSERT 0 1
postgres=# select * from test;
id | name
----+------
1 |
1 |    2
2 |    2
(3 行记录)

postgres=# rollback;
ROLLBACK
postgres=# select * from test;
id | name
----+------
1 |
1 |    2
(2 行记录)

2)还可以直接关闭自动提交的功能
\set AUTOCOMMIT off  --注意,AUTOCOMMIT要大写。
示例:
postgres=# \set AUTOCOMMIT off
postgres=#
postgres=#
postgres=# insert into test values(2,2);
INSERT 0 1
postgres=# select * from test;
id | name
----+------
1 |
1 |    2
2 |    2
(3 行记录)

postgres=# rollback;
ROLLBACK
postgres=# select * from test;
id | name
----+------
1 |
1 |    2
(2 行记录)

3.得到psql命令行中具体执行的SQL语句
启动psql时加上-E参数,或者在命令行中使用\set ECHO_HIDDEN on|off命令。
[postgres@single ~]$ psql -E
psql (9.6.1)
Type "help" for help.

postgres=# \d
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','v','m','S','f','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
**************************

List of relations
Schema | Name | Type  |  Owner
--------+------+-------+----------
public | test | table | postgres
public | txx  | table | postgres
(2 rows)

postgres=# \set ECHO_HIDDEN off
postgres=# \d
List of relations
Schema | Name | Type  |  Owner
--------+------+-------+----------
public | test | table | postgres
public | txx  | table | postgres
(2 rows)

postgres=# \set ECHO_HIDDEN on
postgres=# \d
********* QUERY **********
SELECT n.nspname as "Schema",
c.relname as "Name",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as "Type",
pg_catalog.pg_get_userbyid(c.relowner) as "Owner"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','v','m','S','f','')
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND n.nspname !~ '^pg_toast'
AND pg_catalog.pg_table_is_visible(c.oid)
ORDER BY 1,2;
**************************

List of relations
Schema | Name | Type  |  Owner
--------+------+-------+----------
public | test | table | postgres
public | txx  | table | postgres
(2 rows)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: