假设现在有这么一个场景,两个账户之间进行转账,如果转账成功就更新余额,如果转账失败就回滚,要求使用PreparedStatement 来完成这个操作
代码如下:
public class JDBCTransaction {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet res = null;
try {
ResourceBundle rb = ResourceBundle.getBundle("resource/db");
// 1、注册驱动
String driver = rb.getString("driver");
Class.forName(driver);
// 2、获取连接
String url = rb.getString("url");
String user = rb.getString("user");
String password = rb.getString("password");
conn = DriverManager.getConnection(url, user,password );
conn.setAutoCommit(false);// 设置事务提交方式是手动提交
// 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();
int a = 10/0;
ps.setInt(1, 10000);
ps.setString(2, "act-002");
count += ps.executeUpdate();
System.out.println(count==2?"转账成功":"转账失败");
conn.commit();// 如果没有出现异常,就提交事务
} catch (ClassNotFoundException e) {
if (conn!=null){
try {
conn.rollback();// 如果出现异常,就回滚事务
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
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();
}
}
}
}
}
db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bjpowernode
user=root
password=******
解释:
Connection接口中有三个方法分别是:setAutoCommit(boolean autoCommit)、commit() 、rollback()
setAutoCommit官方解释:
Sets this connection’s auto-commit mode to the given state.
commit官方解释:
Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
rollback官方解释:
Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
这些方法都被实现接口的类继承了,所以可以直接使用,setAutoCommit中的布尔值如果是false的话,就可以实现事务的手动提交,当事务结束的时候可以使用commit方法进行事务的手动提交,如果执行过程中出现异常,那就在catch语句块中执行事务的回滚,这样就实现了JDBC编程中加入事务
来源:CSDN
作者:明快de玄米61
链接:https://blog.csdn.net/qq_42449963/article/details/103644607