Create a batch update in JDBC : Batch Update « Database SQL JDBC « Java






Create a batch update in JDBC

  
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
  public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = null;
    try {
      conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");
      conn.setAutoCommit(false);
      Statement st = conn.createStatement();

      st.addBatch("INSERT INTO products (id, name, quantity, price) VALUE ('1', 'M', 10.99, 20)");
      st.addBatch("INSERT INTO products (id, name, quantity, price) VALUE ('2', 'D', 15.99, 19)");
      st.addBatch("INSERT INTO products (id, name, quantity, price) VALUE ('3', 'T', 5.99, 25)");
      st.addBatch("INSERT INTO products (id, name, quantity, price) VALUE ('4', 'S', 8.99, 50)");

      int[] updateCounts = st.executeBatch();
      conn.commit();
    } catch (SQLException e) {
      if (conn != null) {
        conn.rollback();
      }
      e.printStackTrace();
    } finally {
      if (conn!= null) {
        conn.close();
      }
    }
  }
}

   
    
  








Related examples in the same category

1.Batch Update Insert
2.Batch update: add Batch commands
3.Check Batch Update Result
4.Batch Update Demo
5.Batch update for MySQL
6.Deal with batch update exception and results
7.Demo Prepared Statement Add Batch MySQL
8.Statement Batch Update
9.Determining If a Database Supports Batching
10.Prepared Statement With Batch Update