25.3. The Statement and PreparedStatement Interfaces

In this section you're going to look in more detail at the Statement and PreparedStatement interfaces.

You'll start with the Statement interface, where you'll learn about the methods that allow you to constrain the query and how to handle data definition and data manipulation. Next, you'll look at the PreparedStatement, explore the differences between static and dynamic statements, and work with the PreparedStatement interface.

25.3.1. The Statement Interface

You were introduced to the Statement interface in the previous chapter. The Statement interface defines a set of methods that are implemented by an object returned to your program when you call the createStatement() method for the Connection object:

try {
  Statement queryStatement = connection.createStatement();
  // ...
} catch(SQLException sqle) {
  System.err.println(sqle);
}

Like pretty much every other method defined by JDBC, this code must be within a try clause and include a catch statement for SQLException.

Once the Statement interface has been created, defining the query is as simple as building a String containing a valid SQL statement and passing that statement as the argument to the executeQuery() method of the Statement object. The SQL query can be a literal, or it can be a String value that you build at run time, as was the case in the InteractiveSQL application in the previous chapter, where the application obtains the SQL string from the text field just before ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.