Reputation: 193
I have put the querying part in a separate function which handles try,catch and connection in one place. Recently i started seeing that the result set returned is empty but within the method it is not empty. Is this an improper way of passing result set?
public synchronized ResultSet executeQry(String query) {
try {
Connection conn = DriverManager.getConnection(myUrl, user, pass);
Class.forName(myDriver);
Statement st = conn.prepareStatement(query);
System.out.println("executing query: " + query);
ResultSet rs = st.executeQuery(query);
System.out.println("result set is empty?" + resultSetEmpty(rs));
return rs;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
I am calling this method like so
ResultSet tableDataRS = executeQry("SELECT * FROM dummy_table");
System.out.println("tableData is empty? :"+resultSetEmpty(tableDataRS));
When run, the log shows that within executeQry the result set is not empty but once returned it is empty
executing query: SELECT * FROM dummy_table
result set is empty?false
tableDataRS is empty? :true
Upvotes: 0
Views: 547
Reputation: 193
Thanks to comments, i found the issue. I am moving the cursor from before start of content of result set to check if it is empty in the method "resultSetEmpty()" so when i later actually tried to use it, it was already pointing to the end so there is no content to use. This can be fixed by adding "beforeFirst()" to result set. Here is the method edited with the method call to move cursor to before the first record.
public Boolean resultSetEmpty(ResultSet rs) {
boolean isEmpty = true;
try {
while (rs.next()) {
isEmpty = false;
rs.beforeFirst();
break;
}
} catch (SQLException e) {
e.printStackTrace();
}
return isEmpty;
}
Upvotes: 1