首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入SQLException时更新POSTGRES ::Updating

插入SQLException时更新POSTGRES ::Updating
EN

Stack Overflow用户
提问于 2013-09-12 23:40:42
回答 2查看 128关注 0票数 1

我是Postgres的新手。我正在尝试使用java / postgres jdbc执行以下代码(适用于MySQL):

代码语言:javascript
复制
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”是“PreparedStatement”。

我的成绩是25P02。

使用Postgres可以做到这一点吗?有什么解决方法吗?

非常感谢,

琼。

EN

回答 2

Stack Overflow用户

发布于 2013-09-12 23:54:44

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

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

代码语言:javascript
复制
conn.rollback();

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

票数 1
EN

Stack Overflow用户

发布于 2013-09-12 23:57:10

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

代码语言:javascript
复制
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();
 }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18768676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档