295次插入后,关闭连接并创建一个不超过最大光标的新连接

问题描述

以前的开发人员在代码中留下了此消息。

它运行create语句并执行查询,并在295条记录后创建新连接。

以下是Java代码:

private void dbUpdate() throws SQLException,Exception {
        Statement st = null;
        String sql = "";
        int count = 0;
        try {
            getNewConnection();
            conn.setAutoCommit(false);
            for (Iterator it = sqlList.iterator(); it.hasNext();) {
                if (count < 295) { //Closes connection and creates a new one so as not to exceed max cursors
                    count++;
                } else {
                    st.close();
                    conn.close();
                    getNewConnection();
                    count = 0;
                }
                sql = (String) it.next();
//                System.out.println(sql + " insert count=" + count);
                st = conn.createStatement();
                try {
                    st.executeQuery(sql);
                } catch(Exception ex) {
                    Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE,sql);
                    Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE,ex.getLocalizedMessage(),ex);
                    sb.append("\n").append("Error SQL:" + sql + "|LocalizedMessage:" +ex.getLocalizedMessage());
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(LoadMain.class.getName()).log(Level.INFO,sql);
            Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE,ex);
            throw new SQLException(ex);
        } catch (Exception ex) {
//            Logger.getLogger(loadMain.class.getName()).log(Level.SEVERE,ex);
            throw new Exception(ex);
        } finally {
            try {
                st.close();
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(LoadMain.class.getName()).log(Level.SEVERE,null,ex);
            }
        }
    }

重新连接背后是否有任何逻辑? (另外,开发人员将autocommit设置为false,但是没有看到提交或回滚,而仅使用st.close()方法。)

任何人都可以开导

解决方法

似乎开发人员尝试实现连接池,现在可以轻松地将其与DBCP / Hikari /其他数据库连接池集成。

例如,您不需要在DAO级别/方法上进行提交 如果代码是通过@Transactional方法调用的,或者在服务级别处理了commit。

此外,您不能依靠close进行提交或回滚,使用不同的oracle驱动程序可能会有不同的结果

根据javadoc,在调用close方法之前,您应该尝试提交或回滚。否则结果将由实现定义。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...