新建一个账户表

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 @   __sunshine  阅读(236)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示