为什么在这种情况下oracle会话阻塞

问题描述 投票:0回答:1
try{
   PreparedStatement ps = conn.prepareStatement("delete from table_1 where key =123"));
   ps.execute();
   ps = conn.prepareStatement("delete from table_2 where key =123"));
   ps.execute();
}catch(Exception e){
  ......
}finally{
   ps.close();
   conn.close();

}

我的代码有一个问题,我实际上使用了2条预处理语句,但仅关闭了最后一条,而在生产环境中运行我的代码时,有可能oracle db会话被阻塞,任何人都可以告诉我为什么没有任何闭合的Preparedstatement会导致db会话阻塞?我确实关闭了连接,并且在会话阻止时也没有例外。.

oracle session jdbc prepared-statement
1个回答
1
投票

您是否启用了自动提交?否则,第一个执行将等待事务命令。仅将准备好的语句用于一个事务时,这始终是一个好习惯。

try{
   PreparedStatement ps = conn.prepareStatement("delete from table_1 where key =123"));
   ps.execute();
   // autocommit enabled? -> conn.commit(); or only at the end of both executions (*1)- if there is a need

   PreparedStatement ps2 = conn.prepareStatement("delete from table_2 where key =123"));
   ps2.execute();
   // autocommit enabled? -> conn.commit(); (*1) commits both (ps/ps2)

} catch(Exception e){
    // rollback needed?
    conn.rollback();
} finally{
   // or commit here.. but be aware of your transaction needs for both ps
   closeStatement (ps);
   closeStatement (ps2);
   conn.close();
}

void closeStatement (PreparedStatement ps) {
  try {
    ps.close();
  } catch (Exception e) {
    <<log something or others>> 
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.