Queries and Results

Any time you want to issue SQL queries, an instance of either the Statement or the PreparedStatement class is required. Objects of both of these classes can be obtained from Connection object that represents the database that you wish to query. The Connection object's createStatement method returns a Statement object; the prepareStatement method returns a PreparedStatement.

Executing a query is done by invoking the executeQuery method of your Statement or PreparedStatement object. An executeQuery returns a ResultSet object that contains the entire result of the query. ResultSets are usually iterated over, with an action being performed on each row.

Example 7-1 illustrates the process of using a Statement object and Example 7-2 shows the use of a PreparedStatement object.

Example 7-1. Processing a Simple Query in JDBC

Statement stmt = con.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();
stmt.close();

Example 7-2. Processing a Simple Query in JDBC

int foovalue = 500;
PreparedStatement pstmt = 
   con.prepareStatement("SELECT * 
   FROM mytable WHERE columnfoo = ?");
pstmt.setInt(1, foovalue);
ResultSet rs = pstmt.executeQuery();

while (rs.next())
{
   System.out.println("Column 1: " + rs.getString());
}

rs.close();
pstmt.close();

Notes on Using the Statement and PreparedStatement Interfaces

The following must be considered when using the Statement or PreparedStatement interface:

Notes on Using the ResultSet Interface

The following must be considered when using the ResultSet interface: