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

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

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