Transaction Management
Transaction management is an important aspect of database systems to ensure data integrity. A transaction is a logical unit of work that consists of one or more database operations. These operations are either all executed successfully or none of them are, ensuring that the data remains consistent.
In Java, you can manage transactions using JDBC. Here's an example of how to perform transaction management with JDBC:
TEXT/X-JAVA
1<<code>>Let's break down the code:
- Before executing any SQL statements, we establish a connection to the database using the
DriverManager.getConnectionmethod. - We set the
auto-commitproperty of the connection tofalseusingsetAutoCommit(false). This allows us to manually control the transaction boundaries. - We execute our SQL statements within a try-catch block. If any exception occurs, we catch it and roll back the transaction using
connection.rollback(). - If everything is executed successfully, we commit the transaction using
connection.commit().
By properly managing transactions, we can ensure data integrity and handle errors in database operations effectively.
xxxxxxxxxx48
}class Main { public static void main(String[] args) { // replace with your Java logic here // Transaction management code Connection connection = null; try { // Replace with your database URL, username, and password String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; // Establish a connection to the database connection = DriverManager.getConnection(url, username, password); // Set auto-commit to false to enable transaction management connection.setAutoCommit(false); // Execute SQL statements within a transaction Statement statement = connection.createStatement(); statement.execute("DELETE FROM employees WHERE age < 30"); statement.execute("UPDATE employees SET salary = salary + 1000 WHERE age >= 30"); // Commit the transaction connection.commit(); System.out.println("Transaction committed successfully."); } catch (Exception e) { // Rollback the transaction if (connection != null) {OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment



