Making the Most of JDBC with WebRowSet
Pages: 1, 2, 3, 4, 5
Using Simple ResultSet
With this introduction in mind, let me show you a simple example. All examples discussed in this article are developed with Eclipse 3.1.0 using JDK 5.0 with Oracle database version 10.2 in Windows XP. See the resources section for the sample code and actual output file.
Let's consider a simple database table that defines four columns to store some information, called "student." The following table shows the query used to retrieve already populated results.
SQL> select * from student:
| ID | FNAME | LNAME | AGE |
| 200 | Jack | Dakota | 21 |
| 100 | John | Doe | 26 |
Now for starters, let's write a Java class that connects to the database containing the student table and retrieve its records.
public class DatasourceConnector {
public static void main(String[] args) {
Connection con =null;
OracleDataSource ds =null;
try {
ds = new OracleDataSource();
ds.setUser("<dbuser>");
ds.setPassword("<password>");
ds.setURL(
"jdbc:oracle:thin:@localhost:1521:<sid>");
} catch (SQLException e) {
e.printStackTrace();
}
try {
con = ds.getConnection();
Statement stmt = con.createStatement();
ResultSet rs =
stmt.executeQuery(
"select * from student ");
for (int j=0;
j<rs.getMetaData().getColumnCount();
j++)
{
System.out.print(
rs.getMetaData().
getColumnName(j+1)+"\t");
}
while (rs.next()) {
System.out.print("\n");
for (int i=0;
i< rs.getMetaData().getColumnCount();
i++)
{
System.out.print(
rs.getString(i+1)+"\t");
}
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The Java class in this example instantiates and initializes a connection object, creates a statement containing the query string, and retrieves the result set. You have to supply database user ID, password, and the schema name of the underlying database that are marked within '<…>' for your settings. Save this file as DatasourceConnector.java, compile, and run:
>javac DatasourceConnector.java
>java DatasourceConnector
Should everything go fine, you should see a result similar to this:
| ID | FNAME | LNAME | AGE |
| 200 | Jack | Dakota | 21 |
| 100 | John | Doe | 26 |