• 演示悲观锁(行级锁)机制


    JDBCTest13类:
    	专门进行查询,并且使用行级锁/悲观锁,锁住相关的记录
    JDBCTest14类:
    	负责修改被锁定的记录
    测试:
    	在JDBCTest13中的conn.commit();前添加断点,debug后
    	运行JDBCTest14程序,出现loaded classes are up to date,nothing to reload
    	将JDBCTest13resume pragram后,JDBCTest14程序成功执行更新语句
    
    JDBCTest13类代码:
    	package com.bjpowernode.jdbc;
    
    	import com.bjpowernode.jdbc.utils.DBUtil;
    
    	import java.sql.Connection;
    	import java.sql.PreparedStatement;
    	import java.sql.ResultSet;
    	import java.sql.SQLException;
    
    	/**
    	 * @Author:杨青
    	 * @Time:2021/10/27 11:05
    	 * @Description:
    	 *      这个事务专门进行查询,并且使用行级锁/悲观锁,锁住相关的记录
    	 */
    	public class JDBCTest13 {
    		public static void main(String[] args) {
    			Connection conn=null;
    			PreparedStatement ps=null;
    			ResultSet rs=null;
    			try {
    				//获取连接
    				conn=DBUtil.getConnection();
    				conn.setAutoCommit(false);  //开启事务
    				//获取预处理数据库操作对象
    				String sql="select  ename,job,sal from emp where job=? for update";
    				ps=conn.prepareStatement(sql);
    				ps.setString(1,"manager");
    				//执行sql语句
    				rs=ps.executeQuery();
    				//处理查询结果集
    				while (rs.next()){
    					System.out.println(rs.getString("ename")+","+rs.getString("job")+","+rs.getDouble("sal"));
    				}
    				conn.commit();  //提交事务
    			} catch (SQLException throwables) {
    				throwables.printStackTrace();
    				if(conn!=null){
    					try {
    						conn.rollback();
    					} catch (SQLException e) {
    						e.printStackTrace();
    					}
    				}
    			}finally {
    				DBUtil.close(conn,ps,rs);
    			}
    		}
    	}
    JDBCTest14代码:
    	package com.bjpowernode.jdbc;
    
    	import com.bjpowernode.jdbc.utils.DBUtil;
    
    	import java.sql.*;
    
    	/**
    	 * @Author:杨青
    	 * @Time:2021/10/27 11:06
    	 * @Description:
    	 *      这个程序负责修改被锁定的记录
    	 */
    	public class JDBCTest14 {
    		public static void main(String[] args) {
    			Connection conn=null;
    			PreparedStatement ps=null;
    
    			try {
    				conn= DBUtil.getConnection();
    				conn.setAutoCommit(false);
    				String sql ="update  emp set sal=sal*1.1 where job=?";
    				ps=conn.prepareStatement(sql);
    				ps.setString(1,"manager");
    				int count=ps.executeUpdate();
    				System.out.println("count:"+count);
    				conn.commit();
    			} catch (SQLException throwables) {
    				if(conn!=null){
    					try {
    						conn.rollback();
    					} catch (SQLException e) {
    						e.printStackTrace();
    					}
    				}
    				throwables.printStackTrace();
    			}finally {
    				DBUtil.close(conn,ps,null);
    			}
    		}
    	}
    	
    

      

  • 相关阅读:
    矩阵运算(二维数组)
    AndroidManifest.xml
    单位和尺寸
    java Map集合类
    http相关
    文件管理与XMl、JSON解析
    Handler与多线程
    App内容分享
    Fragment以及懒加载
    广播接收器与短信
  • 原文地址:https://www.cnblogs.com/-slz-2/p/15470907.html
Copyright © 2020-2023  润新知