我们知道oracle中sqlplus里面执行dml语句;是需要提交commit;若错了;也可以回滚rollback; 然而在postgresql里面默认是自动提交;执行完就马上提交了,不能回滚,这样容易导致误操作的发生,有没有什么办法避免这个风险呢?当然有,在psql中默认是打开自动提交的,我们可以关闭自动提交。 2. 操作验证[postgres@oracle2 ~]$ psql -U lottu -d xzfb
psql (9.5.0)
Type "help" for help. xzfb=> create table lottu01(id int);
CREATE TABLE
xzfb=> select * from lottu01;
id
----
(0 rows)
xzfb=> insert into lottu01 values (1001);
INSERT 0 1
xzfb=> rollback
xzfb-> ;
WARNING: there is no transaction in progress
ROLLBACK
xzfb=> select * from lottu01;
id
------
1001
(1 row)
从上面操作下;postgresql是自动提交的;如何关闭呢;执行 \set AUTOCOMMIT off [postgres@oracle2 ~]$ psql -U lottu -d xzfb
psql (9.5.0)
Type "help" for help. xzfb=> \set AUTOCOMMIT off xzfb=> insert into lottu01 values (1002);
INSERT 0 1
xzfb=> commit; --1002此处提交
COMMIT
xzfb=> insert into lottu01 values (1003);
INSERT 0 1
xzfb=> rollback; --1003回滚了
ROLLBACK
xzfb=> select * from lottu01;
id
------
1001
1002
(2 rows)
3. 自动关闭提交如果每次进入psql后都手工设置\set AUTOCOMMIT off比较麻烦,可以把这句设置到.psqlrc文件: [postgres@oracle2 ~]$ cat .psqlrc \set AUTOCOMMIT off [postgres@oracle2 ~]$ 4. 备注
但是这样设置了;也存在不习惯的地方。 1. 操作错误之后;执行正确的dml语句会报错“ERROR: current transaction is aborted, commands ignored until end of transaction block”;避免是执行commit;或者rollback
[postgres@oracle2 ~]$ psql -U lottu -d xzfb
psql (9.5.0)
Type "help" for help. xzfb=> insert into lottu01 values ('1523');
INSERT 0 1
xzfb=> insert into lottu01 values ('a1523'); - -插入字符串 。 ERROR: invalid input syntax for integer: "a1523" LINE 1: insert into lottu01 values ('a1523'); ^ xzfb=> insert into lottu01 values (1523); - -执行正确的dml语句会报错 ERROR: current transaction is aborted, commands ignored until end of transaction block xzfb=> rollback; --避免下面继续报错
ROLLBACK
xzfb=> insert into lottu01 values (1523);
INSERT 0 1
2. 执行ddl语句;也是需要执行commit,当然也可以rollback xzfb=> create table t(id int);
CREATE TABLE
xzfb=> select * from t;
id
----
(0 rows)
xzfb=> \q
[postgres@oracle2 ~]$ psql -U lottu -d xzfb
psql (9.5.0)
Type "help" for help. xzfb=> select * from t; ERROR: relation "t" does not exist LINE 1: select * from t; ^ 3. 上面除了设置关闭自动提交;我们也可以通过begin end;去执行 (责任编辑:最模板) |