1

我是 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 做到这一点吗?任何解决方法?

非常感谢,

琼。

4

2 回答 2

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();
 }
}
于 2013-09-12T15:57:10.027 回答
1

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

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

conn.rollback();

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

于 2013-09-12T15:54:44.413 回答