Transaction example in JDBC in Java


[Learning Notes]

7. JDBC transaction example:

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 {
      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”);
/* The next step should have been where ID = 4, but it was miswritten as WWW ID = 4, so there was a mistake, so it went to catch, but rollback
But it was unsuccessful because it was autocommited mode, so the last sentence ID = 3 changed to 508. */
      s.executeUpdate(“update ACCOUNTS set BALANCE=608 www ID=4”);

      System.out.println(“con = ” + con);
    catch (Exception e) {
        System.out.println(“rollback successfully”);
      }catch (Exception ex)
    finally {
      System.out.println(“successfully in finally”);



The article is reproduced in the original: