What is the use of the method setAutoCommit() in JDBC?


If you commit a database, it saves all the changes that have been done till that particular point.

You can commit a database using the commit() method. Whenever any issue occurs you can revert the database to this point using the rollback() method. By default, some databases commit the databases automatically. But, while managing transactions you need to commit the database manually.

In this scenario you can use the setAutoCommit() method. This method belongs to the Connection interface and, it accepts a boolean value.

If you pass true to this method it turns on the auto-commit feature of the database and, if you pass false to this method it turns off the auto-commit feature of the database.

You can turn of the auto commit feature of databases using this method as:

Con.setAutoCommit(false);

Example

Following program inserts data in to this table using batch processing. Here we set the auto commit false, add the required statements to a batch, execute the batch and then commit the database on our own.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class BatchProcessing_Statement {
   public static void main(String args[])throws Exception {
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //CREATE TABLE Dispatches( Product_Name VARCHAR(255), Name_Of_Customer
      VARCHAR(255), Month_Of_Dispatch VARCHAR(255), Price INT, Location VARCHAR(255));
      //Creating a Statement object
      Statement stmt = con.createStatement();
      //Setting auto-commit false
      con.setAutoCommit(false);
      //Statements to insert records
      String insert1 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
         + "Month_Of_Dispatch , Price, Location) VALUES "
         + "('KeyBoard', 'Amith', 'January', 1000, 'hyderabad')";

      String insert2 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
         + "Month_Of_Dispatch , Price, Location) VALUES "
         + "('Earphones', 'SUMITH', 'March', 500, 'Vishakhapatnam')";

      String insert3 = "INSERT INTO Dispatches( Product_Name , Name_Of_Customer , "
         + "Month_Of_Dispatch , Price, Location) VALUES "
         + "('Mouse', 'Sudha', 'September', 200, 'Vijayawada')";
      //Adding the statements to the batch
      stmt.addBatch(insert1);
      stmt.addBatch(insert2);
      stmt.addBatch(insert3);
      //Executing the batch
      stmt.executeBatch();
      //Saving the changes
      con.commit();
      System.out.println("Records inserted......");
   }
}

Output

Connection established......
Records inserted......

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements