【问题标题】:How to prevent from transaction to close at the catch(Exception e)?如何防止事务在捕获时关闭(异常 e)?
【发布时间】:2016-06-19 22:20:35
【问题描述】:

我正在尝试从 java 向 PosgresSQL 运行查询,但我收到来自 stmt.execute(sql) 的错误

我想执行一个新查询来帮助我打印出失败的特定行,但是当我到达 catch (Exception e) 时,事务被中止。

我无法创建新事务,因为我正在使用临时表。如何防止交易中止?

org.postgresql.util.PSQLException: 错误: 当前事务被中止,命令被忽略直到事务块结束

try (Statement stmt = data.db.getConnection().createStatement()) {
        //  data.db.getConnection().setSavepoint("sp01");
        // insert to fact table
        TableSchema factTableSchema = factInfo.getTableSchema();
        // build SQL
        String sql = "Select * From....";
        try {
            stmt.execute(sql); // this row is failing 
        }
        catch (Exception e) {
            try {
         // now i would like to run a query   only in case arrived here, but the transaction is closed
                      // how could i prevent from trasanction to close ?
                ResultSet rs = stmt.executeQuery(" SELECT Bla,Bla From..");
                Log.debug("");
            }
            catch (Exception e2) {
                Log.debug("");
            }
        }

【问题讨论】:

  • 创建一个新的声明。
  • 你得到了什么异常,因为select 通常不会导致异常,除非你有语法错误。请注意,PostgreSQL 会因错误而中止事务,并且除了启动新事务之外没有任何恢复。
  • 第一个例外是整数超出范围。
  • 使用正确的sql来避免它?因为这正是我对交易的期望。失败时中止和回滚...
  • @Fildor 这是个人喜好问题,有些人(以及许多数据库系统)将事务提交或错误后回滚留给程序处理(例如,当可以采取一些纠正措施时)。

标签: java sql postgresql connection


【解决方案1】:

在执行查询之前,在第二个 try 块中创建一个新语句。

Statement stmt = data.db.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(" SELECT Bla,Bla From..");

ResultSet 需要连接并处于活动状态才能执行next();

【讨论】:

  • 你必须在查询中提交什么?
  • 即使是查询,您也需要事务来获得正确的可见性保证。在 JDBC 中,您要么有自动提交,要么禁用自动提交,然后程序员通过显式调用提交或回滚来决定事务结束。
猜你喜欢
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 2017-01-12
相关资源
最近更新 更多