Performing Transactions - Java JDBC

Java examples for JDBC:Transaction

Introduction

Set Connection object autocommit to false and then perform the transactions.

Once you've successfully performed each of the transactions, then commit the Connection object.

Otherwise, roll back each of the transactions that have taken place.

Demo Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Main {
  static Connection conn = null;

  public static void main(String[] args) {
    boolean successFlag = false;
    try {/*from  w w  w  . j  a  v a2  s  .  co m*/

      conn = getConnection();
      conn.setAutoCommit(false);
      successFlag = insertRecord("1", "test", "test", "Text");
      if (successFlag == true) {
        successFlag = insertRecord(null, "test", "test", "Text");
      }
      // Commit Transactions
      if (successFlag == true)
        conn.commit();
      else
        conn.rollback();
      conn.setAutoCommit(true);
    } catch (java.sql.SQLException ex) {
      System.out.println(ex);
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
    }

  }

  private static boolean insertRecord(String recipeNumber, String title,
      String description, String text) {
    String sql = "INSERT INTO RECIPES VALUES("
        + "NEXT VALUE FOR RECIPES_SEQ, ?,?,?,?)";
    boolean success = false;
    try (PreparedStatement pstmt = conn.prepareStatement(sql);) {
      pstmt.setString(1, recipeNumber);
      pstmt.setString(2, title);
      pstmt.setString(3, description);
      pstmt.setString(4, text);
      pstmt.executeUpdate();
      System.out.println("Record successfully inserted.");
      success = true;
    } catch (SQLException ex) {
      success = false;
      ex.printStackTrace();
    }
    return success;

  }

  public static Connection getConnection() throws SQLException {
    Connection conn = null;
    String hostname = null;
    String port = null;
    String database = null;
    String username = null;
    String password = null;
    String driver = null;
    String jdbcUrl;
    if (driver.equals("derby")) {
      jdbcUrl = "jdbc:derby://" + hostname + ":" + port + "/" + database;
    } else {
      jdbcUrl = "jdbc:oracle:thin:@" + hostname + ":" + port + ":" + database;
    }
    conn = DriverManager.getConnection(jdbcUrl, username, password);
    System.out.println("Successfully connected");
    return conn;
  }
}

Related Tutorials