views:

25

answers:

2

Am I correct in thinking that for a database with n USERS, the following code results in at least n interations with the database?

Statement stmt = con.createStatement();
ResultSet srs = stmt.executeQuery(
    "SELECT FAVOURITE_COLOR FROM USERS");
while (srs.next()) {
        //performSomeAction on srs.getString("FAVOURITE_COLOR");
}

Would it then also be possible to extract the FAVOURITE_COLOR from all users in 1 I/O interaction with the database? And if so would that posssibly cause an memory overflow in the program if there are too many users?

+1  A: 

Why can't you just get all the favorite color records at once?

ResultSet srs = stmt.executeQuery(
    "SELECT USERID, FAVOURITE_COLOR FROM USERS");

Actually after further thought this depends on the platform and or DBMS you are talking about. You may need to give more information for an intelligent answer. Some Platforms will get all the rows at once and let you cycle through them, some will only pull rows as you move to them.

Roadie57
So depending on the createStatement implementation, the executeQuery call may cause a memory overflow. Are there also methods that analyse the code, and can automatically split a query up into chunks? (for clarity, is a query is always retrieving data? or would you call it is select query then?)
I think you are talking JAVA specific I was thinking more generically. I am not a JDBC or JAVA guy you may want to tag your question with more language/platform/database type info
Roadie57
+2  A: 

Your sample code does a single roundtrip to the database.

In a simple implementation, executeQuery will wait for the entire dataset to be retrieved from the database. Then each call to next will move immediately to the next row.

Justice