The Statement and PreparedStatement classes described in the previous section can be used to perform updates and database modifications in addition to queries.
To change data already in a database (that is, to perform an SQL INSERT, UPDATE, or DELETE), the executeUpdate method of Statement and PreparedStatement objects must be used instead of executeQuery. The executeUpdate() method is similar to executeQuery in that a statement is sent to the database for execution, but is different in that it does not return a ResultSet. Instead, it returns the number of rows affected by the INSERT, UPDATE, or DELETE. Example 7-3 illustrates using executeUpdate to perform a DELETE.
Example 7-3. Performing an SQL DELETE with executeUpdate
int foovalue = 500; PreparedStatement pstmt = con.prepareStatement("DELETE FROM mytable WHERE columnfoo = ?"); pstmt.setInt(1, foovalue); int rowsDeleted = pstmt.executeUpdate(); System.out.println(rowsDeleted + " rows deleted"); pstmt.close(); |
SQL CREATE and DROP statements can be executed with either the execute method or the executeUpdate method. The execute method is like executeQuery and executeUpdate, but it returns nothing at all. Example 7-4 shows dropping a table using the Statement's execute method.
Example 7-4. Dropping a Table With execute
Statement stmt = con.createStatement(); stmt.execute("DROP TABLE mytable"); stmt.close(); |