By default, the auto commit property of the database connection is set to true. So if you want to rollback the transaction in case there is an exception, you have to set the auto commit to false.
The following example is reference from www.java2s.com. This is a very good website where you can find many useful resources about Java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("*** Start ***");
// Set the JDBC driver and database driver path
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/spain";
// Set the database username and password
String user = "<username>";
String password = "<password>";
// Create the SQL statement
StringBuilder sb = new StringBuilder("");
sb.append("INSERT INTO cities (city_id, city_name) ");
sb.append("VALUES (103, 'Segovia'); ");
sb.append("INSERT INTO cities (city_id, city_name) ");
sb.append("VALUES (104, 'Toledo'); ");
// Initialise the Connection object
Connection con = null;
// Load the JDBC driver
try {
Class.forName(driver);
} catch(Exception E) {
System.out.println("Unable to load JDBC driver: " + driver);
}
// Execute the SQL statement
try {
con = DriverManager.getConnection(url,user,password);
// set auto commit to false
con.setAutoCommit(false);
Statement smt = con.createStatement();
smt.executeUpdate(sb.toString());
smt.close();
// commit before closing the database connection
con.commit();
System.out.println("Transaction commit.");
} catch(SQLException SE) {
if (con != null) {
// rollback if exception occurs
con.rollback();
System.out.println("Transaction rollback.");
}
System.out.println("Fail to execute the SQL statement");
} finally {
if (con != null && !con.isClosed()) {
con.close();
}
}
System.out.println("*** End ***");
}
}
In this example, the database has changed from Postgresql to MySQL just by editing the JDBC connection string and the url path. Please note that you have to also include the MySQL Connector/J driver in the Java project.
