2-JDBC中的事务 2022-11-14 JDBC 事务 0 Comments Word Count: 471(words) Read Count: 2(minutes) 一、简要介绍 how? 12345678910111213141516//1.在获取连接后,设置自动提交为off connection.setAutoCommit(false);//2.在异常处理中进行回滚。try{ }catch(SQLException e){ coonection.rollback(); }//3.没有问题在 sql执行的最后进行提交connectio 案例 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374package com.hspedu.jdbc.transaction_;import com.hspedu.jdbc.utils.JDBCUtils;import org.junit.jupiter.api.Test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;/*** @author 韩顺平* @version 1.0* 演示 jdbc 中如何使用事务*/public class Transaction_ { /没有使用事务. @Testpublic void noTransaction() {//操作转账的业务//1. 得到连接Connection connection = null;//2. 组织一个 sqlString sql = "update account set balance = balance - 100 where id = 1";String sql2 = "update account set balance = balance + 100 where id = 2";PreparedStatement preparedStatement = null;//3. 创建 PreparedStatement 对象try {connection = JDBCUtils.getConnection(); // 在默认情况下,connection 是默认自动提交preparedStatement = connection.prepareStatement(sql);preparedStatement.executeUpdate(); // 执行第 1 条 sqlint i = 1 / 0; //抛出异常preparedStatement = connection.prepareStatement(sql2);preparedStatement.executeUpdate(); // 执行第 3 条 sql} catch (SQLException e) {e.printStackTrace();} finally {//关闭资源 DBCUtils.close(null, preparedStatement, connection);}}//事务来解决@Testpublic void useTransaction() {//操作转账的业务//1. 得到连接Connection connection = null;//2. 组织一个 sqlString sql = "update account set balance = balance - 100 where id = 1";String sql2 = "update account set balance = balance + 100 where id = 2";PreparedStatement preparedStatement = null;//3. 创建 PreparedStatement 对象try {connection = JDBCUtils.getConnection(); // 在默认情况下,connection 是默认自动提交//将 connection 设置为不自动提交connection.setAutoCommit(false); //开启了事务preparedStatement = connection.prepareStatement(sql);preparedStatement.executeUpdate(); // 执行第 1 条 sqlint i = 1 / 0; //抛出异常preparedStatement = connection.prepareStatement(sql2);preparedStatement.executeUpdate(); // 执行第 3 条 sql //这里提交事务connection.commit();} catch (SQLException e) {//这里我们可以进行回滚,即撤销执行的 SQL//默认回滚到事务开始的状态. System.out.println("执行发生了异常,撤销执行的 sql");try {connection.rollback();} catch (SQLException throwables) {throwables.printStackTrace();}e.printStackTrace();} finally {//关闭资源JDBCUtils.close(null, preparedStatement, connection);}}}