package com.wxl.test;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestJdbc3 {
@Test
public void test() {
//配置信息
//解决中文乱码:useUnicode=true&characterEncoding=utf-8
String url = "jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "root";
Connection connection = null;
try {
//1、加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2、连接数据库,代表 数据库
connection = DriverManager.getConnection(url, username, password);
//通知数据库开启事务 false开启事务==sql: start transaction
connection.setAutoCommit(false);
String sql = "update money set money=money-100 where user='A'";
connection.prepareStatement(sql).executeUpdate();
String sql2 = "update money set money=money+100 where user='B'";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();//以上两条sql都执行成功就提交
} catch (Exception e) {
try {
//如果出现异常就通知数据库回滚事务
assert connection != null;
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
JavaWeb 事务操作案例
最新推荐文章于 2022-10-17 16:54:48 发布