JDBC Auto-Commit Off

Go back to: Code Samples
// For conciseness, this code omits error checking 
 
   // Turn auto-commit off
   con.setAutoCommit(false);
 
   // Create a Statement object
   stmt = con.createStatement();
 
   // Prepare an INSERT statement for multiple executions
   sql = "INSERT INTO employees VALUES (?, ?, ?)";
   prepStmt = con.prepareStatement(sql);
 
   // Set parameter values before execution
   prepStmt.setInt(1, 20);
   prepStmt.setString(2, "Employee20");
   prepStmt.setInt(3, 100000);
   prepStmt.executeUpdate();
 
   // Change parameter values for the next execution
   prepStmt.setInt(1, 21);
   prepStmt.setString(2, "Employee21");
   prepStmt.setInt(3, 150000);
   prepStmt.executeUpdate();
   prepStmt.close();
 
   // Manual commit
   con.commit();     
 
   // Execute a SELECT statement. A prepare is unnecessary
   // because it’s executed only once.
   sql = "SELECT id, name, salary FROM employees";
 
   // Fetch the data
   resultSet = stmt.executeQuery(sql);
   while (resultSet.next()) {
 
      System.out.println("Id: " + resultSet.getInt(1) +
                         "Name: " + resultSet.getString(2) +
                         "Salary: " + resultSet.getInt(3));
   }
   System.out.println();
   resultSet.close();
 
   // Prepare the UPDATE statement for multiple executions
   sql = "UPDATE employees SET salary = salary * 1.05 WHERE id = ?";
   prepStmt = con.prepareStatement(sql);
 
   // Execute the UPDATE statement for each
   // value of index between 0 and 9
   for (int index = 0; index < 10; index++) {
      prepStmt.setInt(1, index);
      prepStmt.executeUpdate();
   }
 
   // Manual commit
   con.commit();     
 
   // Execute a SELECT statement. A prepare is unnecessary
   // because it’s only executed once.
   sql = "SELECT id, name, salary FROM employees";
 
   // Fetch the data
   resultSet = stmt.executeQuery(sql);
   while (resultSet.next()) {
 
      System.out.println("Id: " + resultSet.getInt(1) +
                         "Name: " + resultSet.getString(2) +
                         "Salary: " + resultSet.getInt(3));
   }
   System.out.println();
 
   // Close the result set
   resultSet.close();
 
   }
   finally {
 
   closeResultSet(resultSet);
   closeStatement(stmt);
   closeStatement(prepStmt);
   }
 
}




Like what you see? Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis

Book Content Copyright © 2009 by Prentice Hall PTR. All rights reserved. | Corporate Sponsor DataDirect Technologies.