
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Connection setAutoCommit Method with Example
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.
Parameter
This method accepts a boolean value as a parameter. 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.
//Turning off the auto-commit Con.setAutoCommit(false); //Turning on the auto-commit Con.setAutoCommit(true);
To change 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);
Following JDBC program establishes a connection with the database and turns off the auto-commit.
Example
import java.sql.Connection; import java.sql.DriverManager; public class Connection_setAutoCommit { 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); System.out.println("Auto commit value is: "+con.getAutoCommit()); } }
Output
Connection established...... Auto commit value is: false