如果要 *** 作某些数据,先提前锁定这些数据,其他任何事务都不能对该数据进行修改,不允许并发;
SELECT * FROM `login` WHERE l_id>3 FOR UPDATE;
代表login表中id大于3的数据被锁定,不能被修改;
乐观锁:演示悲观锁demo:
public class JdbcTest5 {
public static void main(String[] args) {
PreparedStatement ps = null;
Connection conn = null;
ResultSet rs = null;
try {
conn = DBUtils.connect();
conn.setAutoCommit(false);
String sql = "SELECT * FROM `login` WHERE l_id>3 FOR UPDATE";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
System.out.print(rs.getString("l_id") + "----" + rs.getString("l_nick"));
System.out.println();
}
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
e.printStackTrace();
} finally {
DBUtils.close(conn, ps, rs);
}
}
}
public class JdbcTest4 {
public static void main(String[] args) {
PreparedStatement ps = null;
Connection conn = null;
ResultSet rs = null;
try {
conn = DBUtils.connect();
conn.setAutoCommit(false);
String sql = "update login set l_nick=? where l_id=?";
ps = conn.prepareStatement(sql);
ps.setString(1, "哈雷彗星");
ps.setInt(2, 7);
int c = ps.executeUpdate();
System.out.println("改变条数" + c);
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
} finally {
DBUtils.close(conn, ps, rs);
}
}
}
在commit行加断点再执行JdbcTest4.java,程序会停止运行,直到断点执行后续 *** 作,JdbcTest4的程序才会继续执行;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)