Tutorialspoint

1 Answer
Rishi Raj

If you commit a database, it saves all the changes that have been done till that particular point. By default, some databases commits/saves the changes done automatically. You can turn off/on the auto-commit using the setAutoCommit() method of the Connection interface.

The getAutocommit() method of the Connection interface is used to get the current value of the auto-commit in this connection.

To get the auto-commit value −

Register the driver using the registerDriver() method of the DriverManager class as −

//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

Get the connection using the getConnection() method of the DriverManager class as −

//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");

Turn off/on the auto-commit using the setAutoCommit() method as −

//Setting the auto commit on
con.setAutoCommit(true);
//Setting the auto commit off
con.setAutoCommit(false);

Get the current auto-commit value using the getAutoCommit() method as −

con.getAutoCommit();

Following JDBC program establishes a connection with the database and turns off the auto-commit and retrieves the current auto-commit value (which is false ).

Example

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.