简体   繁体   中英

try/catch/finally with connection.close()

I need to return the data from method first and then call the connection,but warning tells me: "This method should return a result of type ResultSet», adding a return to the end of the method, after the close, but if you write it in such a way that the warning still exists. Maybe i should remove this all and use incapsulation in different way? Here is a method

public ResultSet doSQLQuery(String query) throws ClassNotFoundException{

    Class.forName("com.mysql.jdbc.Driver");

    String SQLQuery = query;

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    try{
        connection = DriverManager.getConnection(DB_URL,login,password);

        statement = connection.prepareStatement(SQLQuery);
        resultSet = statement.executeQuery();

        return resultSet; //return from this place doesnt possible(?)

    } catch (SQLException e) {
        System.err.println("SQLException caught");
        e.printStackTrace();
    }finally {
        if (resultSet != null)
            try { resultSet.close(); }
            catch (SQLException ignore) { }
        if (statement != null)
            try { statement.close(); }
            catch (SQLException ignore) { }
        if (connection != null)
            try { connection.close(); }
            catch (SQLException ignore) { }
    }
}

upd: chose changing return type to string as a solution

We can fix this method so that it returns a reference to a resultset. But this method is closing the resultset. The reference isn't going to be usable by the caller.

This code pattern, opening a resultset, closing the resultset, and returning a reference to the closed resultset isn't going to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM