用过oracle或mysql的人都知道在sqlplus或mysql中,做一个dml语句,如果发现做错了,还可以rollback;掉,但在PostgreSQL的psql中,如果执行一个dml,没有先运行begin;的话,一执行完就马上提交了,不能回滚,这样容易导致误操作的发生,有没有什么办法避免这个风险呢?当然有,在psql中默认是打开自动提交的,我们可以关闭自动提交,方法如下:
设置\set AUTOCOMMIT off
test=# create table test1 (x int);
CREATE TABLE
Time: 0.593 ms
test=# select * from test1;
x
---
(0 rows)
Time: 0.309 ms
test=# rollback;
ROLLBACK
Time: 1.501 ms
test=# select * from test1;
ERROR: relation "test1" does not exist
LINE 1: select * from test1;
^
Time: 0.376 ms
这儿我们需要注意的是,不同步Oracle,PG的DDL事务一样是可以回滚的,并没有隐式提交的概念,这儿我们需要注意下
test=# \d
List of relations
Schema | Name | Type | Owner
--------+------+-------+-------
public | foo | table | kiwi
public | test | table | kiwi
(2 rows)
设置\set AUTOCOMMIT off
test=# create table test1 (x int);
CREATE TABLE
Time: 0.593 ms
test=# select * from test1;
x
---
(0 rows)
Time: 0.309 ms
test=# rollback;
ROLLBACK
Time: 1.501 ms
test=# select * from test1;
ERROR: relation "test1" does not exist
LINE 1: select * from test1;
^
Time: 0.376 ms
这儿我们需要注意的是,不同步Oracle,PG的DDL事务一样是可以回滚的,并没有隐式提交的概念,这儿我们需要注意下
test=# \d
List of relations
Schema | Name | Type | Owner
--------+------+-------+-------
public | foo | table | kiwi
public | test | table | kiwi
(2 rows)