package com.hspedu.jdbc;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
/**
* @author: guorui fu
* @versiion: 1.0
*/
public class tranaction {
@Test
public void tranactionUse(){
//在try-catch外声明,方便关闭调用
Connection connection = null;
PreparedStatement preparedStatement = null;
//sql语句
String sql = "insert into admin values (?,?)";
String sql2 = "insert into admin values (?,?)";
try {
//建立连接
connection = JDBCUtils.getConnection();
//关闭自动提交事务
connection.setAutoCommit(false);
//第一句sql执行
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"merry");
preparedStatement.setString(2,"45621");
preparedStatement.executeUpdate();
//第二句sql执行
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.setString(1,"fgr");
preparedStatement.setString(2,"66666");
preparedStatement.executeUpdate();
//提交事务
connection.commit();
} catch (SQLException throwables) {
//出现异常进行回滚,撤销执行的sql语句,默认回滚到事务开始状态
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throw new RuntimeException(throwables);
} finally {
//关闭资源
JDBCUtils.close(null,connection,preparedStatement);
}
}
}
JDBC事务处理
最新推荐文章于 2023-07-10 20:31:47 发布