1 public void selectREPEATABLE() { 2 Connection conn = null ; 3 PreparedStatement ppst = null ; 4 Connection conn1 = null ; 5 PreparedStatement ppst1 = null ; 6 try { 7 conn = getConn(); 8 conn.setAutoCommit(false); 9 conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); 10 //数据更新前查询 11 String select = "select * from testClass where id = 2 "; 12 ResultSet result1 = conn.prepareStatement(select).executeQuery(); 13 //打印查询数据 14 while(result1.next()){ 15 System.out.println("conn(REPEATABLE) before update" + "\n" + 16 "count = " + result1.getInt(2)); 17 } 18 //数据更新 19 conn1 = getConn(); 20 String sql1 = "update testClass set name = 'hello' where id = 2"; 21 ppst1 = conn1.prepareStatement(sql1); 22 ppst1.execute(sql1); 23 //数据更新后查询 24 ResultSet result2 = conn.prepareStatement(select).executeQuery(); 25 while(result2.next()){ 26 System.out.println("conn(REPEATABLE) after update" + "\n" + 27 "count = " + result2.getInt(2)); 28 } 29 conn.commit(); 30 } catch (SQLException e) { 31 e.printStackTrace(); 32 } finally { 33 try { 34 if (conn != null){ 35 conn.close(); 36 } 37 if (ppst != null){ 38 ppst.close(); 39 } 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } 43 } 44 }
TRANSACTION_REPEATABLE_READ:在一个事务中进行查询时,不允许读取其他事务update的数据,允许读取到其他事务提交的新增数据。
根据你的需求,你应该用TRANSACTION_READ_COMMITTED