O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required