在java代码中实现对数据库事务的控制
默认情况下,数据库连接处于自动提交模式。每个sql语句一旦被执行便提交给数据库。一旦命令提交,就无法对其进行回滚操作。在使用事务时需要关闭这个默认值。
package preparedStament; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import org.junit.Test; import bean.User_cursetom; import JDBCutils.JdbcUtils; /** * @author ztr * @version 创建时间:2021年4月1日 下午8:41:04 * 类说明 */ /** */ public class TransactionTest { /** * 考虑数据库的事务 * * @param clazz * @param sql * @param args * @return */ public <T> T GetInstance(Connection connection, Class<T> clazz, String sql, Object... args) { PreparedStatement prepareStatement = null; // 获取结果集 ResultSet resultSet = null; try { prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } resultSet = prepareStatement.executeQuery(); // 获取元数据 ResultSetMetaData metaData = resultSet.getMetaData(); // 通过metaData获取结果集中的列数 int columnCount = metaData.getColumnCount(); if (resultSet.next()) { T newInstance = clazz.newInstance(); for (int i = 0; i < columnCount; i++) { // 获取列值 Object columnValue = resultSet.getObject(i + 1); // 获取每列的列名 String columnName = metaData.getColumnName(i + 1); // 利用反射 Field field = clazz.getDeclaredField(columnName); // 考虑该属性是否为私有 field.setAccessible(true); field.set(newInstance, columnValue); } return newInstance; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 关闭资源 JdbcUtils.closeResource1(null, prepareStatement, resultSet); } return null; } public void update(Connection connection, String sql, Object... args) { // 获取数据连接 // 预编译sql语句返回preparedStatement PreparedStatement prepareStatement = null; try { prepareStatement = connection.prepareStatement(sql); // 填充占位符 // prepareStatement.setObject的下标从1开始 for (int i = 0; i < args.length; i++) { prepareStatement.setObject(i + 1, args[i]); } // 执行 prepareStatement.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 资源的关闭 JdbcUtils.closeResource(null, prepareStatement); } } @Test public void test1() throws Exception { Connection connection = JdbcUtils.getConnection(); // 获取事务的隔离级别 System.out.println(connection.getTransactionIsolation()); // 取消事务的自动提交 // 设置事务的隔离级别 connection .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); connection.setAutoCommit(false); String sql = "select id,balance from user_cursetom where id = ?"; User_cursetom getInstance = GetInstance(connection, User_cursetom.class, sql, 1); System.out.println(getInstance); } @Test public void test2() throws Exception { Connection connection = JdbcUtils.getConnection(); // 取消事务的自动提交 connection.setAutoCommit(false); String sql = "update user_cursetom balance set balance = 1000 where id = ?"; update(connection, sql, 1); Thread.sleep(15000); System.out.println("修改结束"); connection.rollback(); connection.commit(); } }
笨鸟先飞