Inserting Rows into a Database Table Using a Prepared Statement and Batch Update - Java JDBC

Java examples for JDBC:Batch SQL

Description

Inserting Rows into a Database Table Using a Prepared Statement and Batch Update

Demo Code


import java.awt.Graphics;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {
  public void m() {
    try {/*  w ww  . ja  v a2s. com*/
      Connection connection = null;
      Statement stmt = connection.createStatement();
      // Prepare a statement to insert a record
      String sql = "INSERT INTO my_table (col_string) VALUES(?)";
      PreparedStatement pstmt = connection.prepareStatement(sql);

      // Insert 10 rows
      for (int i=0; i<10; i++) {
          // Set the value
          pstmt.setString(1, "row "+i);

          // Insert the row
          pstmt.executeUpdate();
      }
    } catch (SQLException e) {
    }
  }
}

Related Tutorials