/** * 模拟账户:Tom账户加钱+100,marry账户减钱-100 * 开启事务 */ public class jdbcTransaction { public static void main(String[] args) { // 不使用事务,进行账户的增加 Connection connection = null; PreparedStatement preStatement = null; connection = JDBCUtils.getConnection(); String reduce = "update account set money = money - ? where name = ?"; String increase = "update account set money = money + ? where name = ?"; Savepoint a = null; try { connection.setAutoCommit(false); preStatement = connection.prepareStatement(reduce); a = connection.setSavepoint("a"); preStatement.setString(1,"100"); preStatement.setString(2,"marry"); int i = preStatement.executeUpdate(); System.out.println("marry账户已经扣除了100元"); i = i / 0; preStatement = connection.prepareStatement(increase); preStatement.setString(1,"100"); preStatement.setString(1,"Tom"); i = preStatement.executeUpdate(); System.out.println("Tom已经增加了100元"); } catch (SQLException e) { e.printStackTrace(); try { connection.rollback(a); } catch (SQLException ex) { ex.printStackTrace(); } }finally { JDBCUtils.Close(null,preStatement,connection); } } }
重点:
connection.setAutoCommit(false); //开启事务
a = connection.setSavepoint("a"); // 保存断点
connection.rollback(a); // 回滚断点
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/98947.html