新建一个账户表

create table account (
id int primary key auto_increment,
`name` varchar(40),
money float
);
insert into account(name, money) VALUES ('A',1000);
insert into account(name, money) VALUES ('B',1000);
insert into account(name, money) VALUES ('C',1000);

//数据库事务练习:转账
start transaction ;         #开启事务
update account set money = money - 100 where name ='A';
update account set money = money + 100 where name = 'B';
commit ;

//在代码中实现
@Test
public void test() {
//useUnicode=true&characterEncoding=utf-8用来解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}

try {
//3.通知数据库开启事务
connection.setAutoCommit(false);

String sql = "update account set money = money - 100 where name ='A'";
int i = connection.prepareStatement(sql).executeUpdate();

String sql2 = "update account set money = money + 100 where name = 'B'";
int i1 = connection.prepareStatement(sql2).executeUpdate();
int y = 1/0;    //手动出错,然事务回滚
connection.commit();
System.out.println("success");
} catch (SQLException throwables) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
posted @ 2021-03-12 21:29  __sunshine  阅读(253)  评论(0)    收藏  举报