Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What and when should I specify setFetchSize()?

I see a lot of "best practices" guides for JDBC/MySQL that tells me to specify setFetchSize().

However, I have no idea when to specify, and what(statement, result set) to specify.

Statement.setFetchSize() or PreparedStatement.setFetchSize() 
ResultSet.setFetchSize()
  1. Of these two, what should I specify?
  2. From javadoc and oracle documentation, this is where I get confused about "when"

Javadoc

The default value is set by the Statement object that created the result set. The fetch size may be changed at any time.

Oracle Doc

Changes made to the fetch size of a statement object after a result set is produced will have no affect on that result set.

Please correct me if I am wrong. Does this mean that setFetchSize is only Affective before a query is executed?(Therefore, setFetchSize on a ResultSet is useless? But happens to "The fetch size may be changed at any time"?)

like image 633
Jee Seok Yoon Avatar asked Jan 03 '14 09:01

Jee Seok Yoon


1 Answers

You should read this page from the official docs on result sets. It says

By default, ResultSets are completely retrieved and stored in memory. In most cases this is the most efficient way to operate, and due to the design of the MySQL network protocol is easier to implement. If you are working with ResultSets that have a large number of rows or large values, and cannot allocate heap space in your JVM for the memory required, you can tell the driver to stream the results back one row at a time.

stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                            java.sql.ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(Integer.MIN_VALUE);

The combination of a forward-only, read-only result set, with a fetch size of Integer.MIN_VALUE serves as a signal to the driver to stream result sets row-by-row. After this, any result sets created with the statement will be retrieved row-by-row.

In effect, setting only fetchSize have no effect on the connector-j implementation.

like image 142
Andreas Wederbrand Avatar answered Oct 04 '22 18:10

Andreas Wederbrand