对于事务的处理,其实可以在数据库中写事务,或者用JDBC的事务处理,或者用hibernate或者spring的事务都能很好的解决这一原子问题。 下面就看看这个代码,本文用的是mysql。所以请将表设置为innodb。 package com.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=root"); //点禁止自动提交,设置回退 conn.setAutoCommit(false); Statement stmt = conn.createStatement(); //数据库更新操作1 stmt.executeUpdate("update books set price=price+1 where id=1"); if(1 == 1){ throw new SQLException(); } //数据库更新操作2 stmt.executeUpdate("update books set price=price+1 where id=3"); //事务提交 conn.commit(); }catch(Exception ex) { ex.printStackTrace(); //操作不成功则回退 try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } } } }