官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 芮城县| 长沙市| 都江堰市| 贺州市| 灵武市| 锦屏县| 焦作市| 桦甸市| 铜陵市| 元朗区| 麻城市| 项城市| 靖远县| 永州市| 丹阳市| 深圳市| 阿合奇县| 元氏县| 河北省| 安福县| 乌苏市| 全椒县| 玉田县| 隆林| 永吉县| 霍邱县| 平潭县| 玛沁县| 成武县| 长寿区| 莒南县| 仙居县| 东城区| 汕头市| 辽阳县| 大关县| 石景山区| 林芝县| 四子王旗| 永平县| 五台县|