单一数据库事务代码演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| package os; import java.sql.*; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.Scanner;
public class JDBCtest{ public static void main(String[] args) { Map<String,String> userLoginInfo=initUI(); boolean loginSuccess = login(userLoginInfo); System.out.println(loginSuccess?"登录成功":"登录失败"); } private static boolean login(Map<String,String> data) { ResourceBundle bundle=ResourceBundle.getBundle("JDBC"); Connection conn=null; PreparedStatement stm=null; ResultSet rt=null; try { Class.forName(bundle.getString("driver")); String url=bundle.getString("url"); String name=bundle.getString("name"); String pw=bundle.getString("pw"); conn= DriverManager.getConnection(url,name,pw); conn.setAutoCommit(false); String sql1="Update t_logintest set 登录名 = ? where id=?"; stm=conn.prepareStatement(sql1); stm.setString(1,"王五"); stm.setInt(2,1); int count=stm.executeUpdate(); System.out.println(count); stm.setString(1,"Kangkang"); stm.setInt(2,2); count=stm.executeUpdate(); System.out.println(count); conn.commit();
} catch (Exception e) { if(conn!=null) { try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } } e.printStackTrace(); }finally { if(rt!=null) { try { rt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stm!=null) { try { stm.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
} return false; }
private static Map<String, String> initUI() { Scanner sc=new Scanner(System.in); System.out.println("请输入用户名:"); String userName=sc.nextLine(); System.out.println("请输入密码:"); String pw=sc.nextLine(); Map<String,String> userLoginInfo= new HashMap<>(); userLoginInfo.put("用户名",userName); userLoginInfo.put("密码",pw); return userLoginInfo; }
}
|
行级锁
在sql查询语句后面加for update,把这一行的数据锁住不能动,又叫悲观锁(开启事务后才锁)。
悲观锁:事务必须排队执行,数据锁住了不允许并发
乐观锁:支持并发,事务也不需要排队,只不过需要一个版本号