24.5. Using a PreparedStatement Object

Let's put a prepared statement into action now to go through the mechanics in a practical context. This won't really show the capabilities of this—I'll get to that in the next chapter. You will code an example that executes the same SQL SELECT statement using both Statement and PreparedStatement objects. For each of these, the results will be displayed along with the metadata.

Try It Out: Statements and Metadata

First you'll define an outline of the StatementTest class and its member data. The main() method will instantiate a StatementTest object and then call the methods doStatement() and doPreparedStatement() for that object:

import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class StatementTest {
  public static void main(String[] args) {
    try {
      StatementTest SQLExample = new StatementTest();
      SQLExample.doStatement();
      SQLExample.doPreparedStatement();
    } catch(SQLException sqle) {
      System.err.println("SQL Exception: " + sqle);
    } catch(ClassNotFoundException cnfe) {
      System.err.println(cnfe.toString());
    }
  }

  Connection databaseConnection;                 // Connection to the database
  String driverName;                             // Database driver name
  String sourceURL;                              // Database location
}

Next you can define the StatementTest class constructor. This constructor will assign the driver name and the source URL that defines ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.