Java Connection getAutoCommit Method with Example



In this program, we will establish a connection to a MySQL database and check the current auto-commit setting using the getAutoCommit() method from the Connection interface. We will first disable the auto-commit feature using setAutoCommit(false) and then retrieve the current auto-commit status with getAutoCommit() to verify if it has been successfully disabled.

Steps to use the getAutoCommit() method

Following are the steps to use the getAutoCommit() method ?

  • First, we will import the required java.sql.Connection and java.sql.DriverManager packages.
  • We'll establish a connection to a MySQL database using the DriverManager.getConnection() method.
  • The auto-commit mode will be disabled by calling setAutoCommit(false).
  • Next, we will use the getAutoCommit() method to retrieve the current auto-commit setting.
  • Finally, the program will print out the current auto-commit status.

Java Connection getAutoCommit() method 

Below is the Java program to use the getAutoCommit() method ?

import java.sql.Connection;
import java.sql.DriverManager;
public class Connection_getAutoCommit {
   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......");
      //Setting auto-commit false
      con.setAutoCommit(false);
      //Retrieving the current value of the auto-commit in this connection
      boolean autoCommit = con.getAutoCommit();
      System.out.println("Auto commit value is: "+autoCommit);
   }
}

Output

Connection established......
Auto commit value is: false

Code Explanation

In the above program, we first establish a connection to the MySQL database by using DriverManager.getConnection(). Once the connection is established, we disable the auto-commit feature using con.setAutoCommit(false). This means that database transactions will not be committed automatically. We then call the getAutoCommit() method to check whether auto-commit is enabled or not. The output shows that the auto-commit value is false, confirming that it has been disabled.

Updated on: 2024-10-18T11:56:37+05:30

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements