http://www.brentozar.com/archive/2009/09/whats-on-my-bookshelf/
// For conciseness, this code omits error checking // 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(); // A commit occurs because auto-commit is on // Change parameter values for the next execution prepStmt.setInt(1, 21); prepStmt.setString(2, "Employee21"); prepStmt.setInt(3, 150000); prepStmt.executeUpdate(); // A commit occurs because auto-commit is on prepStmt.close(); // 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(); // Whether a commit occurs after a SELECT statement // because auto-commit is on depends on the driver. // It’s safest to assume a commit occurs here. // Prepare the UPDATE statement for multiple executions sql = "UPDATE employees SET salary = salary * 1.05 WHERE id = ?"; prepStmt = con.prepareStatement(sql); // Because auto-commit is on, // a commit occurs each time through loop // for total of 10 commits for (int index = 0; index < 10; index++) { prepStmt.setInt(1, index); prepStmt.executeUpdate(); } // 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(); // Whether a commit occurs after a SELECT statement // because auto-commit is on depends on the driver. // It’s safest to assume a commit occurs here. } finally { closeResultSet(resultSet); closeStatement(stmt); closeStatement(prepStmt); } }













