zoukankan      html  css  js  c++  java
  • dljd_021_jdbc中如何使用行级锁

    一、jdbc中使用行级锁的步骤

      1.1必须将自动提交方式改为手动提交

      1.2查询语句后面使用for update(引起事务、启动行级锁) 比如: select * from user where userid in(10001,10002) for update;的意思是启动行级锁,锁住userid为10001和10002的这两条数据。

      1.3启动行级锁的目的是只有当前事务才能修改锁住的数据。

      1.4结束事务(提交|回滚)的时候释放行级锁。

    二、jdbc中使用行级锁的示例

      

    package edu.aeon.jdbc;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    
    import edu.aeon.aeonutils.AeonJdbcUtils;
    /**
     * [说明]:修改jdbc中事务的提交方式
     * @author aeon
     */
    public class TestJDBC {
        /**
         * @throws SQLException 
         */
        public static void jdbc_insert() throws SQLException{
            Connection connection=null;
            PreparedStatement preparedStatement = null;
            try {
                connection = AeonJdbcUtils.getMySqlConnection();
                //设置事务的提交方式为手动提交
                connection.setAutoCommit(false);
                String sql="select userid,username,userpw from user where userid in(?,?) for update";
                //将sql语句进行预编译然后保存到preparedStatement对象中
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setInt(1, 10001);
                preparedStatement.setInt(2, 10002);
                preparedStatement.executeQuery();
                sql="update user set username='hjs' where userid in(?,?)";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setInt(1, 10001);
                preparedStatement.setInt(2, 10002);
                int rowCount=preparedStatement.executeUpdate();
                connection.commit();
                System.out.println("成功修改了"+rowCount+"条数据!");
                
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                connection.rollback();
                System.out.println("本次操作失败!");
                e.printStackTrace();
            }finally {
                AeonJdbcUtils.closeDB(null, preparedStatement, connection);
            }
        }
        public static void main(String[] args) {
            try {
                jdbc_insert();
            } catch (SQLException e) {
                System.out.println("本次操作失败!");
                e.printStackTrace();
            }
        }
    }

    运行结果截图:

      

      启动行级锁的目的是只能让当前事务修改数据、其它事务不能对锁住的数据做修改操作!

    如有任何疑问可联系邮箱: 给我发邮件、或直接联系QQ:1584875179 || 点返回首页

  • 相关阅读:
    asp.net C# 实现阿里大鱼和云片网短信接口类
    asp.net C# 实现微信接口权限开发类
    asp.net C# 实现微信服务器配置
    php学习资料
    阿里云ECS升级OpenSSL记录
    Docker(十三):OpenStack部署Docker集群
    Docker(十二):Docker集群管理之Compose
    Docker(十一):Docker实战部署HTTPS的Tomcat站点
    Docker(十):Docker安全
    Docker(九):Docker容器卷插件
  • 原文地址:https://www.cnblogs.com/aeon/p/10083585.html
Copyright © 2011-2022 走看看