Java Reference
In-Depth Information
Example 18-5. UserQuery.java
public
public class
class UserQuery
UserQuery {
public
public static
static void
void main ( String [] fn )
throws
throws ClassNotFoundException , SQLException , IOException {
// Load the database driver
Class . forName ( JDConstants . getProperty ( "jabadot.jabadb.driver" ));
System . out . println ( "Getting Connection" );
Connection conn = DriverManager . getConnection (
JDConstants . getProperty ( "jabadot.dburl" ));
Statement stmt = conn . createStatement ();
ResultSet rs = stmt . executeQuery (
"SELECT * from jabadb where name='ian'" );
// Now retrieve (all) the rows that matched the query
while
while ( rs . next ()) {
// Field 1 is login name
String name = rs . getString ( 1 );
// Password is field 2 - do not display.
// Column 3 is fullname
String fullName = rs . getString ( 3 );
System . out . println ( "User " + name + " is named " + fullName );
}
rs . close ();
// All done with that resultset
stmt . close ();
// All done with that statement
conn . close ();
// All done with that DB connection
System . exit ( 0 );
// All done with this program.
}
}
Note that a ResultSet is tied to its Connection object; if the Connection is closed, the
ResultSet becomes invalid. You should either extract the data from the ResultSet before
closing it or cache it in a CachedRowSet (for more on RowSet s, see Storing Results in a
RowSet ) .
Search WWH ::




Custom Search