Home Tutorial Java Jdbc Jdbcexamples JDBC Autocommit

 
 

JDBC Autocommit
Posted on: April 3, 2006 at 12:00 AM
Advertisement
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.

Advertisement

Related Tags for JDBC Autocommit:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 3, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com