JDBC PreparedStatement – Групповые операции (с Maven)

Групповые операции с PreparedStatement не отличаются от групповых операций в Statement, за исключением того, что запросы необходимо предварительно готовить. Пример вставки нескольких записей:

String QUERY = "INSERT INTO USERS_TABLE "
    		+ "(ID, USER_NAME) VALUES "
    		+ "(?, ?)";

Connection connection = getConnection();	
PreparedStatement connection.setAutoCommit(false);

statement = connection.prepareStatement(QUERY);
statement.setInt(1, 1);
statement.setString(2, "User_1");
statement.addBatch();

statement = connection.prepareStatement(QUERY);
statement.setInt(1, 2);
statement.setString(2, "User_2");
statement.addBatch();

statement.executeBatch();
connection.commit();

Полный пример:

package statements;

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

public class StatementsExample {
  private static final String DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
    private static final String CONNECTION_STRING = "jdbc:derby:derbyDB;create=true";
    private static final String QUERY = "INSERT INTO USERS_TABLE "
    		+ "(ID, USER_NAME) VALUES "
    		+ "(?, ?)";
  
  private void run() throws SQLException {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
      connection = getConnection();	
      connection.setAutoCommit(false); // управлять транзакциями будем вручную
      for (int i = 100; i < 110; i++) {
        statement = connection.prepareStatement(QUERY);
        statement.setInt(1, i);
        statement.setString(2, "User_" + i);
        statement.addBatch();
      }
      statement.executeBatch();
      connection.commit();
      System.out.println("Records inserted");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (statement != null) {
        statement.close();
      }
      if (connection != null) {
        connection.close();
      }
    }
  }
  
  private Connection getConnection() throws ClassNotFoundException, SQLException {
    Class.forName(DRIVER_NAME);
    Connection connection = DriverManager.getConnection(CONNECTION_STRING);
    return connection;
  }
  
  public static void main(String[] args) {
    StatementsExample app = new StatementsExample();
    try {
      app.run();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

}
Групповые операции могут использоваться и с другими PreparedStatement.

Зависимости можно получить с помощью Apache Maven, pom.xml приведен ниже:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ru.mydesignstudio</groupId>
  <artifactId>statements</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.12.1.1</version>
        </dependency>
    </dependencies>
</project>