Java PreparedStatement.addBatch()

Syntax

PreparedStatement.addBatch() has the following syntax.

void addBatch()  throws SQLException

Example

In the following code shows how to use PreparedStatement.addBatch() method.


/*  w w  w  .  j  a v  a  2  s .c  om*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Main {
  public static void main(String[] args) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      String url = "jdbc:mysql://localhost/database";
      connection = DriverManager.getConnection(url, "username", "password");

      String sql = "UPDATE employees SET email = ? WHERE employee_id = ?";
      statement = connection.prepareStatement(sql);

      statement.setString(1, "a@a.com");
      statement.setLong(2, 1);
      statement.addBatch();

      statement.setString(1, "b@b.com");
      statement.setLong(2, 2);
      statement.addBatch();

      statement.setString(1, "c@c.com");
      statement.setLong(2, 3);
      statement.addBatch();

      statement.executeBatch();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException e) {
        } // nothing we can do
      }
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
        } // nothing we can do
      }
    }
  }
}




















Home »
  Java Tutorial »
    java.sql »




DatabaseMetaData
ParameterMetaData
PreparedStatement
ResultSet
Timestamp