【问题标题】:why oracle session blocking in such case为什么在这种情况下会阻塞oracle会话
【发布时间】:2019-10-04 17:59:16
【问题描述】:
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 会导致数据库会话阻塞?我确实调用了连接关闭,并且会话阻塞时没有异常..

【问题讨论】:

  • 没有关闭-->没有关闭
  • 来自google,不关闭preparedStatement会导致游标泄漏,有人告诉我游标泄漏会导致oracle会话阻塞吗?
  • 你想避免游标泄漏;你会用完游标。但是是什么让您认为会话被阻止了?
  • 会话阻塞问题仅发生在我们仅添加以下代码 ps = conn.prepareStatement("delete from table_2 where key =123")); ps.execute();
  • “会话被阻塞”是什么意思?您的应用程序挂起?你的表中有外键吗?

标签: oracle session jdbc prepared-statement


【解决方案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>> 
  }
}

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多