如题!
今天工作中遇到问题,在上一条sql语句执行失败后,紧接着执行下一条sql语句,结果报以下异常:
PSQLException: current transaction is aborted, commands ignored until end of transaction block
通过google到stackoverflow,发现原来是因为设置了connection.setAutocommit(false)
这样,postgre数据库在上一个语句执行失败后,会认为当前事务已经被破坏,如果马上开始下一条语句的话,就会报以上错误。
解决办法有:
1. 设置connection.setAutocommit(true)
2. 在执行下一条sql之前,提交一次事务
3. 上一个sql执行失败就抛出异常,不往下继续执行了。
4. Oracle没有以上问题,在某一条语句执行失败后,无视这条失败语句,继续执行
参考以下地址:
start doing statement.execute
keep on truckin, keep using the last connection because what could go wrong?
org.postgresql.util.PSQLException:
ERROR: current transaction is aborted, commands ignored until
end of transaction block
Workarounds:
You have a few options:
-
Simplest solution: Don't be in a transaction. Set the
connection.setAutoCommit(false);
toconnection.setAutoCommit(true);
. It works because then the failed SQL is just ignored as a failed sql statement. You are welcome to fail sql statements all you want and postgresql won't stop you. -
Stay being in a transaction, but when you detect that the first sql has failed, either rollback/re-start or commit/restart the transaction. Then you can continue failing as many sql queries on that database connection as you want.
-
Don't catch and ignore the Exception that is thrown when a sql statement fails. Then the program will stop on the malformed query.
-
Get Oracle instead, Oracle doesn't throw an exception when you fail a query on a connection within a transaction and continue using that connection.