java_行级锁

2021-01-27  本文已影响0人  走停2015_iOS开发

开启俩个程序进行演示

1.程序01启动后开启悲观锁进行查询 在没有提交之前 02会被卡住不能查询
2.等待程序01commit完成后,程序02才能继续执行
public class lockTest01 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = DBUtil.getConnect();
            con.setAutoCommit(false);
            String sql = "select *from t_student where classno = ? for update";
            ps = con.prepareStatement(sql);
            ps.setInt(1,102);
            rs = ps.executeQuery();
            while (rs.next()){
                System.out.println(rs.getString("sno")+","+rs.getString("sname"));
            }
            con.commit();
        } catch (SQLException throwables) {
            try {
                con.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            DBUtil.close(con,ps,rs);
        }
    }
}
public class lockTest02 {
    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement ps = null;
        try {
            con = DBUtil.getConnect();
            con.setAutoCommit(false);
            String sql = "update t_student set grade = grade*0.8 where classno =?";
            ps = con.prepareStatement(sql);
            ps.setInt(1,102);
            int count = ps.executeUpdate();
            System.out.println(count);
            con.commit();
        } catch (SQLException throwables) {
            try {
                con.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            DBUtil.close(con,ps,null);
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读