zoukankan      html  css  js  c++  java
  • JDBC中的事务

    步骤:

    1. 开启新事务
      • 取消隐式事务自动提交的功能(同时会开启个事务):setAutocommit(false)
    2. 编写组成事务的一组SQL语句
    3. 结束事务
      • commit():提交
      • rollback():回滚

    细节:要求开启事务的连接对象和获取命令的连接对象必须是同一个,否则事务无效(有点线程同步的感觉)

    实例:两个转账之间的转账

    //JDBCUtils为封装连接及释放操作的工具类
    public class TestTransaction {
    	//不用事务
    	@Test
    	public void testNoTransaction() throws Exception{
    		//1.获取连接
    		Connection connection = JDBCUtils.getConnection();
    		
    		//2.执行sql语句
    		PreparedStatement statement = connection.prepareStatement("update account set balance = ? where stuname=?");
    		
    		//操作1:账户1的钱-5000
    		
    		statement.setDouble(1, 5000);
    		statement.setString(2, "账户1");
    		
    		statement.executeUpdate();
    		
    		int i = 1/0;//模拟异常
    		
    		//操作2:账户2的钱+5000
    		statement.setDouble(1, 15000);
    		statement.setString(2, "账户2");
    		
    		statement.executeUpdate();
    		
    		//3.释放资源
    		JDBCUtils.close(null, statement, connection);
    	}
    
    	//使用事务
    	@Test
    	public void testTransaction(){
    		Connection connection  = null;
    		PreparedStatement statement = null;
    		
    		try {
    			//1.获取连接
    			 connection = JDBCUtils.getConnection();
    			//①事务的使用步骤1:开启事务
    			
    			connection.setAutoCommit(false);
    			
    			//②事务的使用步骤2:编写sql语句,并且执行
    			
    			 statement = connection.prepareStatement("update account set balance = ? where stuname=?");
    			//操作1:账户1的钱-5000
    			
    			statement.setDouble(1, 5000);
    			statement.setString(2, "账户1");
    			
    			statement.executeUpdate();
    			
    //			int i = 1/0;//模拟异常
    			
    			//操作2:账户2的钱+5000
    			statement.setDouble(1, 15000);
    			statement.setString(2, "账户2");
    			
    			statement.executeUpdate();
    			
    			//③事务的使用步骤3:结束事务(如果没出现异常自会执行到此句)
    			connection.commit();
    		} catch (SQLException e) {
    			try {
    				//一旦出现异常,回滚事务
    				connection.rollback();
    			} catch (SQLException e1) {
    				e1.printStackTrace();
    			}
    		}finally{
                            //释放资源
    			JDBCUtils.close(null, statement, connection);
    		}
    	}
    }
    
    
  • 相关阅读:
    Linux 10字符串命令病毒的处理记录
    Spring的核心模块解析
    干货 | 教你如何监控 Java 线程池运行状态
    关于Spring事物的面试题
    Integer、new Integer() 和 int 比较的面试题
    性能监控工具-JDK命令行工具
    JVM调优总结 -Xms -Xmx -Xmn -Xss
    JVM系列三:JVM参数设置、分析
    JVM—内存溢出、OutOfMemoryError、StackOverflowError
    7种垃圾收集器
  • 原文地址:https://www.cnblogs.com/csyh/p/12410714.html
Copyright © 2011-2022 走看看