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.
The following must be considered when using the Statement interface:
You can use a Statement instance as many times as you want. You could create one as soon as you open the connection, and use it for the connections lifetime. 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 the sections covering Threads and Servlets later in this document if you are thinking of using them, as it covers some important points.
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 spec, you should access a field only once. It's 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 with it.
Once you request another query with the Statement used to create a ResultSet, the currently open instance is closed.
An example is as follows:
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();