JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Performance of Inserting Rows with a ResultSet

This section describes how to measure the performance of inserting rows using a ResultSet object.

Since ResultSet objects can also be used to insert rows, I wrote the following Java sample program to measure the performance of inserting multiple rows using a ResultSet object:

/**
 * MySqlPerformanceResultSet.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.util.*;
import java.sql.*;
import javax.sql.*;
public class MySqlPerformanceResultSet {
  public static void main(String [] args) {
    Connection con = null;
    try {
      com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds 
        = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
      ds.setServerName("localhost");
      ds.setPortNumber(3306);
      ds.setDatabaseName("HerongDB");
      ds.setUser("Herong");
      ds.setPassword("TopSecret");
      con = ds.getConnection();

// Delete all rows from the table
      Statement sta = con.createStatement();
      sta.executeUpdate("DELETE FROM Profile");

// Start the test
     int count = 10000;
     long t1 = System.currentTimeMillis();

// ResultSet to insert rows
      Statement rs = con.createStatement(
        ResultSet.TYPE_FORWARD_ONLY,
        ResultSet.CONCUR_UPDATABLE);

      ResultSet res = rs.executeQuery("SELECT * FROM Profile");
      res.moveToInsertRow();
      Random r = new Random();
      for (int i = 0; i < count; i++) {
        res.updateString("FirstName", 
          Integer.toHexString(r.nextInt(9999)));
        res.updateString("LastName", 
          Integer.toHexString(r.nextInt(999999)));
        res.insertRow();
      }
      rs.close();

// End the test
     long t2 = System.currentTimeMillis();
     System.out.println("ResultSet insert "+count
         +" rows with "+(t2 -t1) +" milliseconds");

      con.close();        
    } catch (Exception e) {
      System.err.println("Exception: "+e.getMessage());
      e.printStackTrace();
    }
  }
}

Here is the result on a Windows XP system with a 997MHz processor. You should compare this with the result from other performance tutorials.

Regular Statement insert 10000 rows with 3062 milliseconds

No surprise here, ResultSet is about 2 times slower than PreparedStatement, see the table below:

Statement           # of inserts   Time in ms.   Comparison
PreparedStatement   10000           1281         100%
Regular Statement   10000           1297         101%
ResultSet           10000           3062         239%

Sections in This Chapter

PreparedStatement Overview

PreparedStatement with Parameters

PreparedStatement in Batch Mode

Performance of Inserting Rows with a PreparedStatement

Performance of Inserting Rows with a Regular Statement

Performance of Inserting Rows with a ResultSet

Dr. Herong Yang, updated in 2007
Performance of Inserting Rows with a ResultSet