使用idea也可以提交事务
数据库连接操作可以查看另外两篇博客,有些如何建立工具类,可以减少代码冗余
先去建立数据库
CREATE TABLE IF NOT EXISTS `account`(
`id` INT(4) NOT NULL AUTO_INCREMENT COMMENT 'id',
`name` VARCHAR(10) NOT NULL COMMENT '用户名',
`money` FLOAT,
PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO account(NAME,money)VALUES('A',1000);
INSERT INTO account(NAME,money)VALUES('B',1000);
INSERT INTO account(NAME,money)VALUES('C',1000);
以下是模拟转账操作
package com.gc;
import com.gc.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestTransction {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st =null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false);
//关闭自动提交 也就是开启事务
String sql1 = "update account set money=money-100 where name ='A'";
st=conn.prepareStatement(sql1);
st.executeUpdate();
//int i=1/0; //万能报错
String sql2 = "update account set money=money+100 where name ='B'";
st=conn.prepareStatement(sql2);
st.executeUpdate();
//事务提交
conn.commit();
System.out.println("转账成功");
} catch (SQLException throwables) {
//如果失败自动回滚
try {
System.out.println("转账失败");
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
}finally {
JdbcUtils.release(conn,st,rs);
}
}
}
这个是转账成功
执行了两次,所以金额真的转过去了 运行了三次 嘻嘻
把那句万能报错取消注释
运行
就会失败
数据库中金额也没有转过去
因为捕捉异常里面 有回滚机制
(小声逼逼:听说idea里面不写回滚操作,如果半路抛出异常,也会回滚,可能那句捕捉异常的句子可写可不写)