Unsupported versions: 7.4 / 7.3 / 7.2 / 7.1
This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for the current version, or one of the other supported versions listed above instead.

8.3. Issuing a Query and Processing the Result

Any time you want to issue SQL statements to the database, you require a Statement instance. Once you have a Statement, you can use the executeQuery() method to issue a query. This will return a ResultSet instance, which contains the entire result. Example 8-1 illustrates this process.

Example 8-1. Processing a Simple Query in JDCB

This example with issue a simple query and print out the first column of each row.

Statement st = db.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while(rs.next()) {
    System.out.print("Column 1 returned ");
    System.out.println(rs.getString(1));
}
rs.close();
st.close();

8.3.1. Using the Statement Interface

The following must be considered when using the Statement interface:

  • You can use a single Statement instance as many times as you want. You could create one as soon as you open the connection and use it for the connection's lifetime. But you have to remember that only one ResultSet can exist per Statement.

  • If you need to perform a query while processing a ResultSet, you can simply create and use another Statement.

  • If you are using threads, and several are using the database, you must use a separate Statement for each thread. Refer to Section 8.7 if you are thinking of using threads, as it covers some important points.

8.3.2. Using the ResultSet Interface

The following must be considered when using the ResultSet interface:

  • Before reading any values, you must call next(). This returns true if there is a result, but more importantly, it prepares the row for processing.

  • Under the JDBC specification, you should access a field only once. It is safest to stick to this rule, although at the current time, the Postgres driver will allow you to access a field as many times as you want.

  • You must close a ResultSet by calling close() once you have finished using it.

  • Once you make another query with the Statement used to create a ResultSet, the currently open ResultSet instance is closed automatically.