DBC中悲观锁介绍附案例详解
了解下DBC中悲观锁:
代码如下:
BDUtils 工具类:
package JDBC;
import java.sql.*;
public class BDUtils {
private BDUtils() {
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection connecTion() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/center", "root", "123456");
}
public static void close(Connection conn, Statement ps, ResultSet rt) throws SQLException {
if (conn != null) conn.close();
if (ps != null) ps.close();
if (rt != null) rt.close();
}
}
实现类一:
package JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDButils {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rt = null;
try {
//获取资源
conn = BDUtils.connecTion();
//手动开启事务
conn.setAutoCommit(false);
String sql = "select * from center_user where center_name like ? for UPDATE";
ps =conn.prepareStatement(sql);
ps.setString(1, "王%");
rt = ps.executeQuery();
while (rt.next()){
System.out.println(rt.getString("center_name"));
}
//提交事务
conn.commit();
} catch (SQLException throwables) {
//回滚事务
if (conn != null){
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
throwables.printStackTrace();
}finally {
try {
BDUtils.close(conn, ps, rt);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
实现类二:
package JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDButilsT {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rt = null;
try {
//获取资源
conn = BDUtils.connecTion();
String sql = "UPDATE center_user SET CENTER_AGE = ? where center_name = ? ";
ps = conn.prepareStatement(sql);
ps.setInt(1, 38);
ps.setString(2, "王涛");
int count = ps.executeUpdate();
System.out.println("共影响:" + count + "行");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
BDUtils.close(conn, ps, rt);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
输出结果:
Lock wait timeout exceeded; try restarting transaction
当实现类一的事务没有提交时, for update 查询语句进行了锁定,可以理解为行级锁锁定,其他任何程序或者线程在事务没有提交时,都不能对包含的数据进行DML操作