JDBC Autocommit


 

JDBC Autocommit

Learn how to use JDBC Autocommit mode with the help of example code.

Learn how to use JDBC Autocommit mode with the help of example code.

JDBC Autocommit Mode

In this tutorial we are discussing about jdbc autocommit mode. Setting the true or false of the JDBC autocommit mode allows the developer to take control on the JDBC transaction.

By default, JBDC autocommit mode is true and it commits the JDBC statement immediately, making it a permanent change. So, for example you are executing more than one statement and the mode is set to true; application will keep on saving the database changes into database permanently. If any of the database statement throws an error it won't rollback the previous transactions. So, to use the JDBC transactions you have to change the jdbc autocommit mode to false.

Here is the example that shows how to se the jdbc autocommit to false and commit or rollback the database transactions.

import java.sql.*;

public class JdbcAutocommit {

    public static void main(String args[]) {

        Connection con = null;
        Statement st = null;


        String url = "jdbc:mysql://localhost:3306/";
        String db = "test";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "root";

        try {
            Class.forName(driver);
            con = DriverManager.getConnection(url + db, user, pass);
            con.setAutoCommit(false);// Disables auto-commit.

            st = con.createStatement();
	        //Execute first statement
            String sql = "insert into abc(id,value)('1','abc')";
            st.executeUpdate(sql);
	        st.close();//

          
            st = con.createStatement();
	        //Execute second statement
            sql = "insert into abc(id,value)('2','xyz')";
            st.executeUpdate(sql);
		    st.close();//


            st.close();
	    con.commit();//Save the changes
            con.close();
        } catch (Exception e) {
			try{
			con.rollback();
			}catch(Exception ex){}//eat the exception
            System.out.println(e);
        }
    }
}

In the above example we studied how to use JDBC Autocommit with the help of example code.

Ads