wow mysql dbc_DBC中悲观锁介绍附案例详解
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操作
總結
以上是生活随笔為你收集整理的wow mysql dbc_DBC中悲观锁介绍附案例详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编译后没有taget文件夹_matcon
- 下一篇: javacurrentmap_Java