POSTGRES ::插入时SQLException更新

时间:2013-09-12 15:40:42

标签: java postgresql jdbc

我是Postgres的新手。我正在尝试使用java / postgres jdbc:

执行以下代码(适用于MySQL)
for (int i = 0; i < arr.size(); i++)
{       
 dtoIdent ident = arr.get(i);

 stIns.setLong(1, idInterface);
 stIns.setString(2, tipo);

 try { stIns.executeUpdate(); } 
 catch (SQLException sqe) 
 { 
  stUpd.setString(1, ident.getTipo());
  stUpd.executeUpdate();
 }
}

连接在autcommit = false中。 'stIns'和'stUpd'是'PreparedStatements'。

我得到的是25P02。

可以用Postgres做到这一点吗?任何解决方法?

非常感谢,

琼。

2 个答案:

答案 0 :(得分:1)

由于您的自动提交是假的,并且您的语句已中止,因此您必须回滚连接,因为它现在处于无效状态。

在catch块中,只需在使用executeUpdate之前执行此操作:

conn.rollback();

但是,这将回滚先前在事务中完成的所有更改。如果这是一个问题,那么你应该在try语句之前创建一个带有conn.setSavepoint()的Savepoint,然后在catch块回滚到该Savepoint。

答案 1 :(得分:1)

为了处理异常并且能够忽略它并执行另一个语句,您需要接受使用SAVEPOINTS的处理。例如:

Savepoint sv = null;
for (int i = 0; i < arr.size(); i++)
{       
 dtoIdent ident = arr.get(i);

 stIns.setLong(1, idInterface);
 stIns.setString(2, tipo);

 try
 {
     // create the savepoint
     sv = your_conn_object.setSavepoint();
     stIns.executeUpdate();
     // release the savepoint, as we don't need it anymore
     your_conn_object.releaseSavepoint(your_conn_object);
 } 
 catch (SQLException sqe) 
 { 
     // We caught an exception, so let's rollback to the savepoint
     your_conn_objectrollback(sv);
     stUpd.setString(1, ident.getTipo());
     stUpd.executeUpdate();
 }
}