Java Reference
In-Depth Information
6.
Run the application by clicking the green play icon or selecting Run Run. Enter 1 for the depart-
ment number.
7.
You will now get the output shown in Figure 9-9.
figure 9-9  
How It Works
The first part of the code is similar to the previous example. The only thing that is different is that a Scanner
object is created (using the java.util.* package) to provide input using the keyboard. The DeptNr variable
stores the number of the department for which you want to list the employees. This is accomplished using
a PreparedStatement object. This object can take parameters that are being input using the keyboard or
from a GUI application. In this example, the statement PreparedStatement
preparedStatement = connection.prepareStatement(query); creates a preparedStatement object
based upon the query string variable, which is defined as follows: String query="select Name, Gender,
DNR from employee where DNR=?";. The question mark in the query variable refers to a value that needs
to be specified before the query can be executed. In this example, this variable will be set to DeptNr (which
was obtained via the keyboard) using the following statement: preparedStatement.setInt(1, DeptNr);.
The prepared statement object can then be executed and the results stored in a resultset object using the fol-
lowing statement: ResultSet rs = preparedStatement.executeQuery(); . A while loop can then be
used to navigate through the results of this resultset object as in the previous example.
sQlJ
SQLJ is built on top of JDBC and allows you to embed SQL statements directly into Java programs.
A preprocessor will then translate the SQL statements into Java/JDBC statements, which are then
further compiled by the Java compiler to bytecode. This is illustrated in Figure 9-10.
 
Search WWH ::




Custom Search