1.悲观锁和乐观锁的概念:
2.演示行级锁机制:
注意:DBUtil类 为博主之前自己写的类:【JDBC】编程(2)--- 写一个JDBC工具类;用 JDBC工具类 实现模糊查询
/*
演示行级锁机制
此程序先开启事务,并使用行级锁锁住“loginName = abc”的那条记录
*/
import java.sql.*;
public class JDBCLock01 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
//锁住“loginName = abc”的这条记录
String sql = "select loginName,loginPwd from t_user where loginName = ? for update";
ps = connection.prepareStatement(sql);
ps.setString(1,"abc");
resultSet = ps.executeQuery();
while (resultSet.next()){
System.out.println("loginName = "+resultSet.getString("loginName")+
",loginPwd = "+resultSet.getString("loginPwd"));
}
//添加断点,让此事务在此暂停10s后结束
Thread.sleep(10000);//使当前线程暂停10000毫秒
connection.commit();
} catch (Exception e) {
if (connection != null) {
try {
connection.commit();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
}finally {
DBUtil.close(connection,ps,resultSet);
}
}
}
"JDBCLock01"控制台情况:
(暂停大约1000毫秒然后输出:)
loginName = abc,loginPwd = 123
Process finished with exit code 0
/*
演示行级锁机制
此程序后开启事务,负责修改被锁定的记录
*/
import java.sql.*;
public class JDBCLock02 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement ps = null;
try {
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
//修改“loginName = abc”的这条记录的密码
String sql = "update t_user set loginPwd = ? where loginName = ?";
ps = connection.prepareStatement(sql);
ps.setString(1,"888");
ps.setString(2,"abc");
int count = ps.executeUpdate();
System.out.println("更新数据"+count+"条");
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
connection.commit();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
}finally {
DBUtil.close(connection,ps,null);
}
}
}
"JDBCLock02"控制台输出结果:
("JDBCLock01"程序结束后输出)
更新数据1条
Process finished with exit code 0
总结:在当前事务中,用行级锁锁住的记录,那么在此事务结束之前,其他事务将无法对“锁住的记录”进行操作(update/delete),但是select可以。