欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java当中JDBC当中的transaction例子

程序员文章站 2023-11-10 15:49:58
[学习笔记] 7.jdbc的transaction例子: import java.sql.*;public class MySQlTransaction1 { public static void main(String[] args) throws SQLException {/*in my sq ......

[学习笔记]

7.jdbc的transaction例子:

import java.sql.*;

public class mysqltransaction1 {

  public static void main(string[] args) throws sqlexception {
/*in my sql: create table accounts(
                id int(4) not null,
                name varchar(15),
                balance int(4),
                primary key(id)
            )  type=innodb;
  insert into accounts values(1,'wangwu',100);
  insert into accounts values(3,'zhangsan',300);
  insert into accounts values(4,'lisi',400);
     */
    connection con = null;
    statement s = null;
    try {
      class.forname("com.mysql.jdbc.driver");
      con = drivermanager.getconnection("jdbc:mysql://localhost:3306/test","root", "1234");
      //s = con.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);
/*by default, whenever execute a sql, it will commit automatically,
public void setautocommit(boolean autocommit) throws sqlexception
sets this connection's auto-commit mode to the given state. if a connection is in auto-commit 
mode, then all its sql statements will be executed and committed as individual transactions. 
otherwise, its sql statements are grouped into transactions that are terminated by a call to
 either the method commit or the method rollback. by default, new connections are in
  auto-commit mode.        */

      s = con.createstatement();

      s.executeupdate("update accounts set balance=508 where id=3");
      system.out.println("333333");
/*下一步中本来应为where id=4, 但是却误写成了www id=4, 所以有错,所以到catch中,但rollback时
 , 却做不成功, 因为是autocommited模式,所以上一句id=3,就做真改成508了。*/      
      s.executeupdate("update accounts set balance=608 www id=4");
      system.out.println("444444");

      system.out.println("con = " + con);
     }
    catch (exception e) {
      try{
        con.rollback();
        system.out.println("rollback successfully");
      }catch (exception ex)
      {
        ex.printstacktrace();
      }
    }
    finally {
      s.close();
      con.close();
      system.out.println("successfully in finally");
    }
  }

}

 

文章转载自原文: