【问题标题】:Data Access Object class getting SQLServerException获取 SQLServerException 的数据访问对象类
【发布时间】:2016-05-03 15:55:29
【问题描述】:

我在执行 sql 语句时得到以下 execption

SQLServerException:服务器无法恢复事务。 描述:69d00000016。

我知道下面的 DAO 实现是不正确的。我想知道以下代码的正确实现是什么,以及我的 connFactory 被声明为 static 的事实是否会导致上述错误。

private static DbConnectionFactory connFactory;

    protected myDAO() {
        myDAO.connFactory = DbConnectionFactoryHome.getHome().lookupFactory("facName");
    }

    public myReturn myAccessMethod(final int cod) throws BaseException {
        Connection conn = null;
        CallableStatement stmt = null;
        ResultSet resSet = null;
        myReturn ret= null;

        try {
            conn = myDAO.connFactory.getConnection();
            stmt = conn.prepareCall("{call name (2)}");
            stmt.setInt(1, cod);
            resSet = stmt.executeQuery();
            if (resSet.next()) {                    
                ret = new myReturn(resSet.getInt("someValue"));                    
            }
        }
        catch (SQLException sqle) {                
            throw new myException(sqle.getMessage(), (Throwable)sqle);
        }
        finally {
            try {
                if (resSet != null) {
                    resSet.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (conn != null) {
                    conn.close();
                }
            }                
        }            
        return ret;
    }

我应该从 connFactory 中删除 static 修饰符还是实现一个单例,这样当再次调用构造函数时工厂不会重新创建?

【问题讨论】:

    标签: java singleton database-connection factory dao


    【解决方案1】:

    我会让您的 DBConnectionFactory 成为单身人士。可以在此处找到如何执行此操作的一个很好的示例:Singleton DB Connectionfactory.

    但是,我不确定您的问题是否在于数据库连接工厂是静态的。它实际上可能与您使用结果集提取结果的方式有关。确保您处理所有结果。 您应该包含更完整的堆栈跟踪。您可能需要查看为什么会得到:“服务器无法恢复事务。”这里有一篇关于如何导致此错误以及如何修复它的文章:Failed to resume transaction

    尝试做这样的事情:

    CallableStatement stmt = connection.prepareCall("{call name (2)}");
    stmt.setInt(1, cod);
    
    stmt.execute();
    
    ResultSet rs = (ResultSet)stmt.getObject(index);
    
    //Loop results
    while (rs.next()) {
      ret = new myReturn(resSet.getInt("someValue")
    }
    

    【讨论】:

    • 我知道在同一个连接中调用另一个语句之前需要处理所有结果,但是在这种情况下,在同一个连接中只能调用一个语句。
    • 当你得到错误时你能发布更多你的堆栈跟踪吗?
    猜你喜欢
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2021-02-20
    • 2021-08-29
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多