Java Reference
In-Depth Information
Adding the setAutoCommit(true) line tells the database management system to commit all
changes automatically. If you compile and execute the modified code, you should get exactly the same
results as you do when you run the original example.
Now modify the code to turn Autocommit off, using setAutoCommit(false ), as shown here:
public void execute(String SQLCommand){
String url = urlRoot+dbName;
try {
Connection con = DriverManager.getConnection(url);
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.execute(SQLCommand);
con.close();
}
catch(SQLException e){
System.err.print(e.getMessage());
}
}
This time, when you run the example, it throws an "Invalid Transaction State" exception, and the
update has not been made. The exception is thrown because we have not terminated the transaction
before closing the connection.
Now alter the code in the try block to the following; the change is made as before, because we have
specifically told the database management system to commit the change:
try {
Connection con = DriverManager.getConnection(url);
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.execute(SQLCommand);
con.commit();
con.close();
}
If you change the try block by replacing the con.commit() with con.rollback() , the change will
be rolled back, so no change will be visible. This time, however, no exception is thrown, as you can
see here:
try {
Connection con = DriverManager.getConnection(url);
Search WWH ::




Custom Search