Showing posts with label Transaction Management. Show all posts
Showing posts with label Transaction Management. Show all posts

Friday, 12 September 2014

JDBC : Transaction Management - Why do we need ?

Enjoying This Tutorial?

Subscribe to our YouTube channel for clear, beginner-friendly Java & JDBC guides!

SUBSCRIBE NOW

What Is a Database Transaction?

In database systems, a transaction represents a single unit of work that contains one or more operations (such as SQL INSERT, UPDATE, or DELETE queries). For a transaction to be successful, either all operations must complete successfully, or none of them should take effect at all.

The Problem: What Happens Without Transaction Management?

Let us look at a simple real-world banking scenario to understand the problem:

  • Dave has an account balance of ₹20,000.
  • Peter has an account balance of ₹30,000.

Dave wants to transfer ₹20,000 to Peter. In backend programming, this transfer requires two separate SQL queries:

  1. Deduct ₹20,000 from Dave's account:
    UPDATE bank_account SET balance = 0 WHERE id = 1;
  2. Add ₹20,000 to Peter's account:
    UPDATE bank_account SET balance = 50000 WHERE id = 2;

Now suppose query #1 runs successfully and Dave's balance becomes 0. But right before query #2 runs, an unexpected system crash, network disruption, or database exception occurs!

The result? Dave lost ₹20,000, but Peter never received it. This causes severe data inconsistency and financial loss.

The Solution: How Transaction Management Protects Your Data

By placing both operations inside a single Transaction Boundary, JDBC ensures complete safety:

  • Commit: If all statements execute without any errors, the transaction is committed, permanently saving the changes to the database.
  • Rollback: If any error or exception occurs anywhere during the process, the transaction is rolled back. Dave's balance is automatically restored, and the database returns to its clean original state.

Key Takeaway

Transaction management in JDBC is essential because it guarantees the ACID properties (Atomicity, Consistency, Isolation, Durability). It protects your applications from partial updates, corrupted data, and inconsistent states.

Recommended JDBC Tutorials

Continue mastering JDBC with these related video tutorials:



Click here to watch in Youtube : https://www.youtube.com/watch?v=nrq_Le39G9g

Click the below Image to Enlarge
JDBC : Transaction Management
JDBC : Transaction Management
JDBC : Transaction Management

JDBC : Transaction Management
JDBC : Transaction Management
JDBC : Transaction Management
See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Wednesday, 27 August 2014

    JDBC Transaction Management Demo

    🚀 Master Java database programming, JDBC transactions, and MySQL!

    🔔 Subscribe to Ram N Java on YouTube

    What Is Transaction Management in JDBC?

    A transaction represents a single unit of work consisting of one or more SQL statements. By default, JDBC connections operate in auto-commit mode, which means every individual SQL statement is permanently committed to the database as soon as it completes execution.

    In real-world business scenarios, multiple SQL operations must succeed together as an atomic unit (Atomicity in ACID properties). If any single statement fails, all previously executed statements in that transaction must be rolled back so that the database remains in a consistent state.

    How to Control Transactions Programmatically

    JDBC provides three primary methods on the java.sql.Connection interface to manage transactions manually:

    • conn.setAutoCommit(false); — Disables automatic committing so you can group multiple operations into a single transaction boundary.
    • conn.commit(); — Permanently applies and persists all SQL statements executed within the transaction.
    • conn.rollback(); — Undoes all changes made within the current transaction if any error or exception occurs.

    Complete Java Source Code Example

    The following Java program connects to MySQL, turns off auto-commit, executes three INSERT statements, and rolls back the transaction if any statement fails:

    package com.ram.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBCTransactionManagementDemo {
    
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL = "jdbc:mysql://localhost:3306/world";
        static final String USER = "root";
        static final String PASS = "root";
    
        public static void main(String[] args) {
            JDBCTransactionManagementDemo demo = new JDBCTransactionManagementDemo();
            demo.addCityInformation();
        }
    
        public void addCityInformation() {
            Connection conn = null;
            Statement stmt = null;
    
            try {
                // Step 1: Register JDBC driver and open connection
                Class.forName(JDBC_DRIVER);
                conn = DriverManager.getConnection(DB_URL, USER, PASS);
    
                // Step 2: Disable auto-commit to take manual control of transactions
                conn.setAutoCommit(false);
    
                stmt = conn.createStatement();
    
                // SQL 1: Insert city record
                String sql1 = "INSERT INTO city (ID, Name, CountryCode, District, Population) "
                            + "VALUES (6000, 'CityA', 'USA', 'DistrictA', 100000)";
                stmt.executeUpdate(sql1);
                System.out.println("SQL 1 executed successfully.");
    
                // SQL 2: Insert city record
                String sql2 = "INSERT INTO city (ID, Name, CountryCode, District, Population) "
                            + "VALUES (6001, 'CityB', 'USA', 'DistrictB', 200000)";
                stmt.executeUpdate(sql2);
                System.out.println("SQL 2 executed successfully.");
    
                // SQL 3: Insert city record
                String sql3 = "INSERT INTO city (ID, Name, CountryCode, District, Population) "
                            + "VALUES (6002, 'CityC', 'USA', 'DistrictC', 300000)";
                stmt.executeUpdate(sql3);
                System.out.println("SQL 3 executed successfully.");
    
                // Step 3: Commit all statements if no exception occurred
                conn.commit();
                System.out.println("Transaction committed successfully!");
    
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
    
                // Step 4: Rollback entire transaction on error
                try {
                    if (conn != null) {
                        System.out.println("Exception encountered! Rolling back all transaction changes...");
                        conn.rollback();
                    }
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            } finally {
                // Step 5: Clean up resources
                try {
                    if (stmt != null) stmt.close();
                    if (conn != null) conn.close();
                } catch (SQLException se) {
                    se.printStackTrace();
                }
            }
        }
    }

    Key Steps & Best Practices

    • Turn Off Auto-Commit First: Always call conn.setAutoCommit(false) before executing any statement in the transaction.
    • Explicit Commit: Call conn.commit() only after all participating statements complete without throwing exceptions.
    • Rollback in Catch Block: Wrap your operations inside a try-catch block and invoke conn.rollback() inside catch to maintain database consistency.
    • Resource Cleanup: Always close statements and connections inside the finally block to prevent resource leaks.

    Related Tutorials You Might Enjoy


    Click here to watch in Youtube : https://www.youtube.com/watch?v=IqnxrRIy99w

    Click the below Image to Enlarge

    JDBCTransactionManagementDemo Project Dir Structure
    JDBC Transaction Management Demo
    JDBC Transaction Management Demo

    JDBCTransactionManagementDemo.java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JDBCTransactionManagementDemo
    {
        // JDBC driver name and database URL
        static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        static final String DB_URL      = "jdbc:mysql://localhost:3306/world";
    
        // Database credentials
        static final String USERNAME    = "root";
        static final String PASSWORD    = "root";
    
        public static void main( String[] args )
        {
            JDBCTransactionManagementDemo jdbcTransactionManagementDemo =
                                                 new JDBCTransactionManagementDemo();
            jdbcTransactionManagementDemo.addCityInformation();
        }
    
        private void addCityInformation()
        {
            Connection connection = null;
            Statement statement = null;
            try
            {
                /*
                 * Register the JDBC driver in DriverManager
                 */
    
                Class.forName(JDBC_DRIVER);
    
                /*
                 * Establish connection to the Database using DriverManager
                 */
    
                connection = DriverManager
                        .getConnection(DB_URL, USERNAME, PASSWORD);
    
                /*
                 * Set auto-commit to false
                 */
                connection.setAutoCommit(false);
    
                String sql1 = "insert into city values(6000,'Bangalore','IND','Karnataka',400000)";
                String sql2 = "insert into city values(6001,'Channai','IND','TamilNadu',200000)";
                String sql3 = "insert into city values(6002,'Thiruvanathapuram','IND','Kerala',800000)";
    
                /*
                 * Execute the query
                 */
                statement = connection.createStatement();
    
                /*
                 * Execute each sql one by one
                 */
                statement.executeUpdate(sql1);
                System.out.println(sql1 + " : Sql1 is Successfully executed");
                statement.executeUpdate(sql2);
                System.out.println(sql2 + ": Sql2 is Successfully executed");
                statement.executeUpdate(sql3);
                System.out.println(sql3 + ": Sql3 is Successfully executed");
    
                /*
                 * If there is no error
                 */
                connection.commit();
    
                System.out
                        .println("Changes are committed and applied to the Database");
    
            }
            catch( SQLException se )
            {
                /*
                 * Handle errors for JDBC
                 */
                try
                {
                    /*
                     * If there is any error.
                     */
                    connection.rollback();
                    System.out
                            .println("Changes are rollbacked and not applied to the Database");
                }
                catch( SQLException e )
                {
                    e.printStackTrace();
                }
                se.printStackTrace();
            }
            catch( ClassNotFoundException e )
            {
                /*
                 * Handle errors for Class.forName
                 */
                e.printStackTrace();
            }
            catch( Exception e )
            {
                try
                {
                    /*
                     * If there is any error.
                     */
                    connection.rollback();
                    System.out
                            .println("Changes are rollbacked and not applied to the Database");
                }
                catch( SQLException e1 )
                {
    
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
            finally
            {
                /*
                 * finally block used to close resources
                 */
                try
                {
                    if( statement != null )
                    {
                        statement.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
                try
                {
                    if( connection != null )
                    {
                        connection.close();
                    }
                }
                catch( SQLException sqlException )
                {
                    sqlException.printStackTrace();
                }
            }
    
        }
    }
    
    
    Output
    insert into city values(6000,'Bangalore','IND','Karnataka',400000) : Sql1 is Successfully executed
    insert into city values(6001,'Channai','IND','TamilNadu',200000): Sql2 is Successfully executed
    insert into city values(6002,'Thiruvanathapuram','IND','Kerala',800000): Sql3 is Successfully executed
    Changes are committed and applied to the Database
    
    
    Environment Used 

    JDK version : 1.7.0_51
    Mysql Server version : 5.6.19 

    To Download JDBCTransactionManagementDemoApp Project Click the below link

    https://sites.google.com/site/javaee4321/jdbc/JDBCTransactionManagementDemoApp.zip?attredirects=0&d=1

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • JDBC Transaction Management

    Master Java & JDBC With Us!

    Subscribe to Ram N Java for practical code demos, database tutorials, and beginner-friendly guides.

    SUBSCRIBE TO CHANNEL

    What Is Transaction Management in JDBC?

    In database programming, a transaction represents a single unit of work. It can group multiple SQL statements together inside what is called a transaction boundary.

    The fundamental rule of transaction management is straightforward:

    • If all SQL statements execute successfully, the changes are saved to the database.
    • If any single statement fails or throws an exception, all changes are discarded, leaving the database completely clean and unaffected.

    Default Auto-Commit Mode vs. Manual Control

    By default, a JDBC Connection operates in Auto-Commit mode (true). In this mode, each SQL statement is committed automatically the moment it finishes executing.

    To group multiple operations into your own custom transaction, you must disable auto-commit:

    connection.setAutoCommit(false);

    Commit vs. Rollback: Key Methods

    The JDBC Connection interface provides two primary methods to manage outcomes:

    • connection.commit(): When all SQL statements inside your transaction boundary execute without error, call commit() to make all updates permanent in the database.
    • connection.rollback(): If an error occurs (such as query 3 failing while queries 1 and 2 succeeded), invoke rollback(). This cancels all pending operations and restores the database to its initial state.

    Understanding ACID Properties

    Transaction management is guided by the four pillars of database integrity:

    1. Atomicity: "All or nothing" — either every statement succeeds, or none of them do.
    2. Consistency: Ensures that the database transitions strictly from one valid, consistent state to another.
    3. Isolation: Each ongoing transaction executes independently without interference from other concurrent transactions.
    4. Durability: Once a transaction is committed, changes remain permanent, even during system crashes or power failures.

    Explore More JDBC Tutorials

    Deepen your understanding of Java database development with these tutorials:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=y1GYvOQBcls

    Click the below Image to Enlarge
    JDBC Transaction Management
    JDBC Transaction Management
    JDBC Transaction Management
    JDBC Transaction Management
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Tutorials