dljd_019_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();
        }
    }
}

运行结果截图:

  

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

转载于:https://www.cnblogs.com/aeon/p/10083585.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值