jdbc操作和开启事务





public
static void test(){ //1.数据库驱动类名的字符串 String driver = "com.mysql.jdbc.Driver"; //2.用户名 String username = root; //3.密码 String password = "root"; //4.加载数据库驱动(加载成功后,会把Driver的实例注册到DriverManager中) try{ Class.forName(driver); Connection conn = null; Statemnet stmt = null;
  //5.获取数据库连接 conn
= DriverManager.getConnection();   //6.获取连接对象
    Statement stmt
= conn.createStatement(); //7.开启手动提交事务
  conn.setAutoCommit(
false); //8.执行sql语句
stmt.executeUpdate(
"update student set money=? where id =?",new int[]{8,1})
  stmt.executeUpdate("update student set money=? where id=?",new int[]{12,2}); //9.提交事务
conn.commit(); }
catch(Exception e){ //10.回滚事务
conn.rollback(); } }

 

posted on 2021-03-05 21:58  想入围城的小码农  阅读(470)  评论(0编辑  收藏  举报