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();
}
}
}
}
转载于:https://my.oschina.net/ranruci/blog/318226