Forgive my lack of creativity when it comes to titeling this problem correctly.
Hi, i’ve spent the last 3 hours trying to figure out this problem, and I think i’ve figured it out, but the solution to it still eludes me. I have this very simple code.
Statement stmt = db.getStatement();
ResultSet queryResult = stmt.executeQuery("SELECT * FROM users");
while(queryResult.next()) {
username = queryResult.getString("username");
password = queryResult.getString("password");
privilege = queryResult.getInt("privilege");
queryResult = stmt.executeQuery("SELECT * FROM division");
while(queryResult.next()) {}
users.add(new User(username, password, privilege));
}
Now, this piece of code is dumbed down to illustrate what the problem is in my code. I don’t have a while loop which contains nothing, obviously.
I’ve come to realize that whenever I want to fetch something from the database, I can only do it with the resultset within one loop. If I write a “nested-resultset-loop”, I either get “Operation… ResultSet closed”, “Cannot find column ‘username'”, or some other error.
I have alot of these nested resultset loops throughout my DAO code, to fetch everything from the database. Since i’m not that strong at MySQL, this was the simple solution (I have VERY little time left to do this program)… Since I used to do similiar back in PHP.
I’m not saying this code is good design, but for the sake of time, I really do not care much at the moment about good class design. So any solution you have in mind, regardless of poor design choice is welcomed.
Another solution would be to split everything up in single loops, because that tends to work (very simple). But that means modifying alot of the code, and i’d prefer this to be the backup plan.
You can’t interleave the resultsets like that, see the API documentation:
I think you’ll be ok if you create separate statements for the different queries. The usual practice that I’ve seen is to have a separate DAO method for each query, in order to keep the DAO methods as simple and as reusable as possible. (That implies that the DAO isn’t in charge of transaction demarcation, but that a higher level component, like a service, controls what’s in a transaction.)