Share on Google+Share on Google+

JDBC Autocommit

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 {
            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 = con.createStatement();
	        //Execute second statement
            sql = "insert into abc(id,value)('2','xyz')";

	    con.commit();//Save the changes
        } catch (Exception e) {
			}catch(Exception ex){}//eat the exception

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



Posted on: April 3, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.