com.microsoft.sqlserver.jdbc.SQLServerException: 在获取结果集的值时连接已关闭

huangapple go评论75阅读模式
英文:

com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed while taking the value of Resultset

问题

public static ResultSet getTestDatafromSQL(String QueryString) throws SQLException {
    Connection conn = null;
    ResultSet resultSet = null;
    try {
        String dbURL = "jdbc:sqlserver://localhost\\sqlexpress;DatabaseName=master;integratedSecurity=true;";
        conn = DriverManager.getConnection(dbURL);
        if (conn != null) {
            DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
            System.out.println("Driver name: " + dm.getDriverName());
            System.out.println("Driver version: " + dm.getDriverVersion());
            System.out.println("Product name: " + dm.getDatabaseProductName());
            System.out.println("Product version: " + dm.getDatabaseProductVersion().toString());
            Statement stmt = conn.createStatement();
            // Create and execute a SELECT SQL statement.
            resultSet = stmt.executeQuery(QueryString);
            System.out.println(resultSet);
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1));
                //return resultSet.getString(1);
            }
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return resultSet;
}
		
Now In another class, I am calling that... 

@Test(enabled = true)
public void query() throws XPathExpressionException, IOException, SQLException {
    ResultSet sql = utilities.getTestDatafromSQL("SELECT ACCOUNT_NO1,CREDIT_LMT from [BCMASTER$] Where CAST(Trim(BCM_CREDIT_LMT) as float) > 5000");
    //System.out.println(sql.first());
    System.out.println("SQLValue:" + sql.getString(1));
    System.out.println("SQLValue:" + sql.getString(2));
}

I am getting FAIL Sat Aug 15 10:25:24 IST 2020 com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed. - Test Case Failed

To read the result set, should the DB connection be open?

From each query, I will get different columns, so is it possible to store the results in an array and return that? Or is returning the ResultSet the only possibility to get the values?

英文:
public static ResultSet getTestDatafromSQL(String QueryString) throws SQLException {
Connection conn = null;
ResultSet resultSet = null;
try {
String dbURL = "jdbc:sqlserver://localhost\\sqlexpress;DatabaseName=master;integratedSecurity=true;";
conn = DriverManager.getConnection(dbURL);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion().toString());
Statement stmt = conn.createStatement();
// Create and execute a SELECT SQL statement.
resultSet = stmt.executeQuery(QueryString);
System.out.println(resultSet);
while(resultSet.next()) {
System.out.println(resultSet.getString(1));
//return resultSet.getString(1);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return resultSet;
}

Now In other class, I am calling that...

@Test(enabled = true)
public void query() throws XPathExpressionException, IOException, SQLException {
ResultSet sql = utilities.getTestDatafromSQL("SELECT ACCOUNT_NO1,CREDIT_LMT from [BCMASTER$] Where CAST(Trim(BCM_CREDIT_LMT) as float) >5000");
//System.out.println(sql.first());
System.out.println("SQLValue:"+sql.getString(1));
System.out.println("SQLValue:"+sql.getString(2));
}

I am getting FAIL Sat Aug 15 10:25:24 IST 2020 <span class='badge white-text red'>com.microsoft.sqlserver.jdbc.SQLServerException: The connection is closed. - Test Case Failed</span>

To read the result set, db connection should be open?

From each query I will get different columns, so is there any possible can we store it in array and return is only possibility or resultset can get the value?

答案1

得分: 3

你在getTestDatafromSQL()方法中关闭了Connection,所以返回ResultSet没有意义。考虑将ResultSet存储在java.util.List中,并且让getTestDatafromSQL()方法返回一个List而不是ResultSet

或者,不要在getTestDatafromSQL()方法中关闭Connection,返回ResultSet,然后调用getTestDatafromSQL()的方法(根据你问题中的代码是query()方法)可以关闭Connection。在ResultSet接口中调用getStatement(),它返回一个Statement,在Statement接口中调用getConnection(),它返回Connection,然后可以关闭它。

另一种选择是使用 CachedRowSet

以下是我对上述第一种选项的实现。

public static List<List<String>> getTestDatafromSQL(String QueryString) throws SQLException {
    Connection conn = null;
    ResultSet resultSet = null;
    List<List<String>> result = new ArrayList<>();
    List<String> row;
    try {
        String dbURL = "jdbc:sqlserver://localhost\\sqlexpress;DatabaseName=master;integratedSecurity=true;";
        conn = DriverManager.getConnection(dbURL);
        if (conn != null) {
            Statement stmt = conn.createStatement();
            // 创建并执行 SELECT SQL 语句。
            resultSet = stmt.executeQuery(QueryString);
            while (resultSet.next()) {
                row = new ArrayList<>();
                row.add(resultSet.getString(1));
                row.add(resultSet.getString(1));
                result.add(row);
            }
        }
    }
    catch (SQLException ex) {
        ex.printStackTrace();
    }
    finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

以下是我对上述第二种选项的实现。

public static ResultSet getTestDatafromSQL(String QueryString) throws SQLException {
    Connection conn = null;
    ResultSet resultSet = null;
    String dbURL = "jdbc:sqlserver://localhost\\sqlexpress;DatabaseName=master;integratedSecurity=true;";
    conn = DriverManager.getConnection(dbURL);
    Statement stmt = conn.createStatement();
    // 创建并执行 SELECT SQL 语句。
    resultSet = stmt.executeQuery(QueryString);
    return resultSet;
}

然后你可以这样调用方法,然后关闭Connection

ResultSet sql = utilities.getTestDatafromSQL("SELECT ACCOUNT_NO1,CREDIT_LMT from [BCMASTER$] Where CAST(Trim(BCM_CREDIT_LMT) as float) > 5000");
// 处理 ResultSet
sql.getStatement().getConnection().close();
英文:

You close the Connection in method getTestDatafromSQL() so no point in returning a ResultSet. Consider storing the ResultSet in a java.util.List and have method getTestDatafromSQL() return a List rather than a ResultSet.

Alternatively, don't close the Connection in method getTestDatafromSQL() and return the ResultSet and the method that calls getTestDatafromSQL() (which is method query() according to the code in your question) can close the Connection. In interface ResultSet call getStatement() which returns a Statement and in interface Statement call getConnection() which returns the Connection and then you can close it.

Another alternative would be to use a CachedRowSet

Here is my implementation of the first option described above.

public static List&lt;List&lt;String&gt;&gt; getTestDatafromSQL(String QueryString) throws SQLException {
    Connection conn = null;
    ResultSet resultSet = null;
    List&lt;List&lt;String&gt;&gt; result = new ArrayList&lt;&gt;();
    List&lt;String&gt; row;
    try {
        String dbURL = &quot;jdbc:sqlserver://localhost\\sqlexpress;DatabaseName=master;integratedSecurity=true;&quot;;
        conn = DriverManager.getConnection(dbURL);
        if (conn != null) {
            Statement stmt = conn.createStatement();
            // Create and execute a SELECT SQL statement.
            resultSet = stmt.executeQuery(QueryString);
            while (resultSet.next()) {
                row = new ArrayList&lt;&gt;();
                row.add(resultSet.getString(1));
                row.add(resultSet.getString(1));
                result.add(row);
            }
        }
    }
    catch (SQLException ex) {
        ex.printStackTrace();
    }
    finally {
        try {
            if (conn != null &amp;&amp; !conn.isClosed()) {
                conn.close();
            }
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

Here is my implementation of the second option.

public static ResultSet getTestDatafromSQL(String QueryString) throws SQLException {
    Connection conn = null;
    ResultSet resultSet = null;
    String dbURL = &quot;jdbc:sqlserver://localhost\\sqlexpress;DatabaseName=master;integratedSecurity=true;&quot;;
    conn = DriverManager.getConnection(dbURL);
    Statement stmt = conn.createStatement();
    // Create and execute a SELECT SQL statement.
    resultSet = stmt.executeQuery(QueryString);
    return resultSet;
}

Then you would call the method and then close the Connection like this:

ResultSet sql = utilities.getTestDatafromSQL(&quot;SELECT ACCOUNT_NO1,CREDIT_LMT from [BCMASTER$] Where CAST(Trim(BCM_CREDIT_LMT) as float) &gt;5000&quot;);
// Handle the ResultSet
sql.getStatement().getConnection.close();

huangapple
  • 本文由 发表于 2020年8月15日 13:07:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63422784.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定