1. 程式人生 > >dljd_019_jdbc中如何使用行級鎖

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

執行結果截圖:

  

  啟動行級鎖的目的是隻能讓當前事務修改資料、其它事務不能對鎖住的資料做修改操作!