WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java JDBC · Intermediate · question 26 of 100

What is the purpose of the setFetchSize() method in JDBC, and when should it be used?

📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

The ‘setFetchSize()‘ method in JDBC is used to specify the number of rows that should be retrieved in a single database round-trip when executing a SELECT statement. By default, JDBC retrieves all the rows at once.

The purpose of this method is to improve the performance of data retrieval by fetching the data in smaller batches. This can be useful when dealing with large result sets or slow networks.

When the ‘setFetchSize()‘ method is used, the driver will retrieve only the number of rows specified in the batch size and keep them in a buffer. As the application iterates through the result set, additional rows are fetched from the database in batches.

For example, consider the following code snippet:

    Statement stmt = conn.createStatement();
    stmt.setFetchSize(100);
    
    ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
    
    while (rs.next()) {
        // process row
    }

In this example, we set the fetch size to 100 rows. As the application processes the result set, the JDBC driver will fetch 100 rows at a time from the database.

It’s important to note that the actual number of rows returned per fetch may be less than the fetch size if there are fewer rows left in the result set. Additionally, not all databases support the ‘setFetchSize()‘ method, and some JDBC drivers may ignore it.

In general, you should consider using the ‘setFetchSize()‘ method when you are dealing with large result sets, slow networks, or when you need to optimize performance. However, it’s important to test your application to determine the optimal fetch size for your specific use case.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java JDBC interview — then scores it.
📞 Practice Java JDBC — free 15 min
📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

All 100 Java JDBC questions · All topics