Java jdbc batch update examples
In Java, you can use JDBC batch updates to execute multiple SQL statements as a single batch. This can be much faster than executing each statement individually.
Here are the steps to use JDBC batch updates in your Java code:
- Import the necessary JDBC classes in your Java code:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException;
- Create a connection to your database using the DriverManager class:
String url = "jdbc:mysql://localhost/mydatabase"; String user = "myuser"; String password = "mypassword"; Connection connection = DriverManager.getConnection(url, user, password);
Replace "jdbc:mysql://localhost/mydatabase" with the URL to your database, and "myuser" and "mypassword" with your database credentials.
- Set the auto-commit mode of the connection to false:
connection.setAutoCommit(false);
This tells the connection that it should not commit each statement individually, but instead wait for an explicit call to the commit() method.
- Create a new PreparedStatement object to execute your SQL queries:
String sql = "INSERT INTO mytable (name, age) VALUES (?, ?)"; PreparedStatement statement = connection.prepareStatement(sql);
Replace "mytable" with the name of your table.
- Add the parameters for your SQL queries using the set methods:
statement.setString(1, "Alice"); statement.setInt(2, 25); statement.addBatch(); statement.setString(1, "Bob"); statement.setInt(2, 30); statement.addBatch();
The addBatch() method adds the current set of parameters to the batch.
- Execute the batch update:
int[] updateCounts = statement.executeBatch();
The executeBatch() method executes the batch and returns an array of update counts for each SQL statement in the batch.
- Call the commit() method to commit the transaction:
connection.commit();
If an exception is thrown, the rollback() method is called to undo any changes made in the batch.
- Close the PreparedStatement and Connection objects:
statement.close(); connection.close();
This frees up any resources used by the objects.
That's it! With these steps, you can use JDBC batch updates in your Java code to execute multiple SQL statements as a single batch.