不进行改造的“在JDBC中加入事务”的代码在:点我就去看
实现的功能是:“假设现在有这么一个场景,两个账户之间进行转账,如果转账成功就更新余额,如果转账失败就回滚,要求使用PreparedStatement 来完成这个操作”
DBUtil 工具类代码:
public class DBUtil {
private static ResourceBundle rb = ResourceBundle.getBundle("resource/db");
// 构造方法私有化,禁止对象实例化
private DBUtil(){}
static {
// 注册驱动,只需要注册一次就可以了
String driver = rb.getString("driver");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return 获取和数据库的连接通道
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
String url = rb.getString("url");
String user = rb.getString("user");
String password = rb.getString("password");
Connection conn = DriverManager.getConnection(url, user,password );
return conn;
}
/**
* 设置事务的手动提交
* @param conn
* @throws SQLException
*/
public static void startTransaction(Connection conn) throws SQLException {
conn.setAutoCommit(false);
}
/**
* 提交事务
* @param conn
* @throws SQLException
*/
public static void commitTransaction(Connection conn) throws SQLException {
conn.commit();
}
/**
* 如果事务出现异常,回滚事务
* @param conn
*/
public static void rollbackTransaction(Connection conn){
if (conn!=null){
try {
conn.rollback();// 如果出现异常,就回滚事务
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
/**
* 释放对象
* @param conn
* @param ps
* @param res
*/
public static void close(Connection conn, PreparedStatement ps, ResultSet res){
if (res!=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
改造之后的JDBC中加入事务的代码:
public class JDBCTransaction {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet res = null;
try {
// 2、获取连接
conn = DBUtil.getConnection();
DBUtil.startTransaction(conn);
// 3、获取预编译的数据库操作对象
String sql = "update t_act set balance= ? where actno= ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, 40000);
ps.setString(2, "act-001");
int count = ps.executeUpdate();
ps.setInt(1, 10000);
ps.setString(2, "act-002");
count += ps.executeUpdate();
System.out.println(count==2?"转账成功":"转账失败");
DBUtil.commitTransaction(conn);
} catch (Exception e) {
DBUtil.rollbackTransaction(conn);
e.printStackTrace();
} finally {
DBUtil.close(conn, ps, res);
}
}
}
里面用到的db.properties代码:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
user=root
password=******