Monday, April 16, 2012

Calling another method to get resultset and closing the connection correctly?

try{
String query= "select user_name from user";
ResultSet rs = queries.performQuery(query);

while(rs.next()){
System.out.println("User Name :" + rs.getString("user_name"));
}


in another class I have something like this:



public ResultSet performQuery(String query) throws SQLException
{
try
{
connection = DriverManager.getConnection(sqlUrl,sqlUser,sqlPassword);
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
}

catch(SQLException ex)
{
}

finally{
close(rs);
close(stmt);
close(connection);
}
return rs;
}


Now I get the error Operation not allowed after ResultSet closed, and it's obviously because I'm closing the rs/stmt/connection.



I don't have my code with me so this is just off the top of my head, disregard any syntax errors and I hope my question is still clear enough.



So my question is this:



If you want to have a method that for example performs queries, and you call that in another method and then do rs.next, what is the appropriate way to close the resultset/stmt/connection? To me it makes sense to close them the performQuery, but that gives me the error.





No comments:

Post a Comment