Wednesday 1 October 2014

Fetch Size

The number of rows of data that a driver copies from the database to the client is called the fetch size.

Statement interface provides 'setFetchSize(int rows)' method to set the number of rows that should be fetched from the database. If you set fetch size to a statement, then the ResultSet objects created using this statement use the same fetch size.

Note :
You can also set the fetch size for ResultSet separately using 'setFetchSize(int rows)' of ResultSet interface.

/* Step 1: Import sql package */
import java.sql.*;

public class SampleApp {
    
    /* Update username, password and driver details here */
    static Connection getConnection() throws ClassNotFoundException, SQLException{
         /* Step 2: Load Driver */
        System.out.println("Loading/Registering driver");  
       
        Class.forName("com.mysql.jdbc.Driver");
         
        /* Step 3: Open connection to database */
        System.out.println("Connecting to database");
        String url = "jdbc:mysql://localhost/world";
        String userName = "root";
        String pasword = "tiger";
        return DriverManager.getConnection(url, userName, pasword);
    }
    
    public static void main(String args[]) throws SQLException, ClassNotFoundException{     
        Connection conn = getConnection();

        Statement stmt = conn.createStatement();
        System.out.println("Default fetch size is " + stmt.getFetchSize());
        stmt.setFetchSize(25);
        System.out.println("Fetch size is " + stmt.getFetchSize());
       
        stmt.close();
        conn.close();
    }
}

Output
Loading/Registering driver
Connecting to database
Default fetch size is 0
Fetch size is 25



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment