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

时间:2017-03-06 05:31:56

标签: oracle session jdbc prepared-statement

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 session有可能阻塞,任何人都可以告诉我为什么没有关闭的Preparedstatement将导致db会话阻塞?我确实将conneciton称为close,并且在会话阻塞时没有异常..

1 个答案:

答案 0 :(得分:2)

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

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>> 
  }
}