Java EE 8 Development with Eclipse
上QQ阅读APP看书,第一时间看更新

Handling transactions

If you want to perform multiple changes to the database as a single unit, that is, either all changes should be done or none, then you need to start a transaction in JDBC. You start a transaction by calling Connection. setAutoCommit(false). Once all operations are executed successfully, commit the changes to the database by calling Connection.commit. If for any reason you want to abort the transaction, call Connection.rollback(). Changes are not done in the database until you call Connection.commit.

Here is an example of inserting a bunch of courses into the database. Although in a real application, it may not make sense to abort a transaction when one of the courses is not inserted, here we assume that either all courses must be inserted into the database or none:

PreparedStatement stmt = con.prepareStatement("insert into Course (id, name, credits) values (?,?,?)"); 
 
con.setAutoCommit(false); 
try { 
  for (Course course : courses) { 
    stmt.setInt(1, course.getId()); 
    stmt.setString(2, course.getName()); 
    stmt.setInt(3, course.getCredits()); 
    stmt.execute(); 
  } 
  //commit the transaction now 
  con.commit(); 
} 
catch (SQLException e) { 
  //rollback commit 
  con.rollback(); 
} 


There is more to learn about transactions than explained here. Refer to Oracle's JDBC tutorial at http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html.