Java POSTGRES::在插入SQLException时更新
我是博士后的新手。我尝试使用java/postgres jdbc执行以下代码(与MySQL一起使用):Java POSTGRES::在插入SQLException时更新,java,postgresql,jdbc,Java,Postgresql,Jdbc,我是博士后的新手。我尝试使用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)
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();
}
}
for(int i=0;i
连接处于AUTCOMIT=false状态。”“Stin”和“stUpd”是“准备好的声明”
我得到一个25P02
有可能对博士后这样做吗?有解决办法吗
非常感谢,
Joan.由于您的自动提交为false,并且您的语句被中止,您必须回滚连接,因为它现在处于无效状态 在catch块中,只需在使用executeUpdate之前执行以下操作:
conn.rollback();
但是,这将回滚以前在事务中所做的所有更改。如果这是一个问题,那么您应该在try语句之前使用conn.setSavepoint()创建一个保存点,然后在catch块中回滚到该保存点。为了处理异常并能够忽略它并执行另一个语句,您需要接受对保存点的处理。例如:
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();
}
}
savepointsv=null;
对于(int i=0;i
为什么希望insert语句失败?因为具有该主键的记录已存在?如果这就是原因,为什么不先检查一下,然后再决定是插入新记录还是更新现有记录?