Java Reference
In-Depth Information
String select = "SELECT * FROM Accounts";
ResultSet results =
while (
System.out.println("Account no."
+ results.getInt(1));
System.out.println("Account holder: "
+ results.getString(3)
+ " "
+ results.getString(2));
System.out.println("Balance: "
+ results.getFloat(4));
System.out.println ();
N.B. Column/fi eld numbers start at 1 , not 0!
Alternatively, column/fi eld names can be used. For example:
System.out.println("Account no."
+ results.getInt("acctNum");
5. Repeat Steps 3 and 4, as Required
The Statement reference may be used to execute other queries (and updates).
6. Close the Connection
This is achieved by calling method close of our Connection object and should be
carried out as soon as the processing of the database has fi nished. For example:
Statement objects may also be closed explicitly via the identically-named method
of our Statement object. For example:
[Note: If using a version of JDBC that precedes version 4, then it will be necessary
to load the JDBC driver explicitly before any of the six steps above are executed.
This is done via static method forName of class Class (!):
E.g., Class.forName("<Driver name>"); ]
We are now almost ready to write our fi rst database access program in Java.
Before we do, though, there is one last issue to consider: exception-handling.
Any of our SQL statements may generate an SQLException , which is a checked
exception, so we must either handle such an exception or throw it.
Search WWH ::

Custom Search