事务管理模型(银行转账)

package cn.itcast.jdbc;

import cn.itcast.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
* @author newcityman
* @date 2019/8/15 - 23:39
* 演示事务
*/
public class JDBCDemo09 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt1=null;
PreparedStatement stmt2=null;
try {
// 1、获取连接
conn = JDBCUtils.getConnection();
// 2、开启事务
conn.setAutoCommit(false);
String sql1="update account set balance =balance-? where id=?";
String sql2="update account set balance =balance+? where id=?";

stmt1 = conn.prepareStatement(sql1);
stmt2 = conn.prepareStatement(sql2);

stmt1.setDouble(1,500);
stmt1.setInt(2,1);

stmt2.setDouble(1,500);
stmt2.setInt(2,2);

stmt1.executeUpdate();
// int i=1/0;
stmt2.executeUpdate();

conn.commit();
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/11361321.html