The code snippet below shows you how to disable auto-commit operation when executing JDBC commands or queries.
package org.kodejava.jdbc;
import java.sql.*;
public class AutoCommitSettingExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
// DO: Get a connection to database, we need to obtain the
// database connection prior to executing any JDBC commands
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
// Disable the auto-commit operation. By default, every statement
// executed against database in JDBC is in auto-commit mode. To
// disable auto-commit set it to false
connection.setAutoCommit(false);
// DO: Execute some other database operation here
String sql = "DELETE FROM book WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setLong(1, 1L);
statement.executeUpdate();
// Finally we must call the commit method explicitly to finish
// all database manipulation operation
connection.commit();
} catch (SQLException e) {
// When some exception occurs rollback the transaction.
connection.rollback();
throw e;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024