Elist.java
import java.io.*;
import java.util.*;
import java.sql.*;
/**
Simple application uses JDBC to build an HTML document listing
employee IDs, names and titles.
*/
class Elist
{
public static void main(String args[])
{
// JDBC driver and DSN for the JDBC-ODBC bridge (to MS Access).
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String dsn = "jdbc:odbc:EmployeeTest";
Connection conn;
Statement stat;
String query;
query =
"SELECT EmpID,EmpName,EmpTitle " +
"FROM Employee " +
"WHERE Active<>0 " +
"ORDER BY nLast";
System.out.println("<HTML>\n" +
"<HEAD>\n" +
"<TITLE>Employees</TITLE>\n" +
"</HEAD>\n" +
"<BODY>\n\n");
try {
Class.forName(driver);
conn = DriverManager.getConnection(dsn,"admin","");
stat = conn.createStatement();
boolean hasResultSet = stat.execute(query);
if (hasResultSet) {
showResultSet(System.out,stat.getResultSet());
}
stat.close();
conn.close();
}
catch (SQLException ex) {
// FIXME Should quote 'ex' here!
System.out.println("<P>" + ex + "</P>");
// Note the use of nested exceptions!
while (ex != null) {
ex.printStackTrace();
ex = ex.getNextException();
}
}
catch (ClassNotFoundException ex) {
// FIXME Should quote 'ex' here!
System.out.println("<P>" + ex + "</P>");
ex.printStackTrace();
}
System.out.println("\n</BODY>\n</HTML>");
}
/**
Write (to <CODE>PrintStream</CODE> '<CODE>out</CODE>') the results
represented by <CODE>ResultSet</CODE> '<CODE>result</CODE>'.
*/
public static void showResultSet(
PrintStream out,ResultSet result)
throws SQLException
{
ResultSetMetaData metaData = result.getMetaData();
int columnCount = metaData.getColumnCount();
out.println("<TABLE BORDER=1 CELLPADDING=2>");
out.print("<TR><TH ALIGN=\"LEFT\">");
for (int i=1; i<=columnCount; i++) {
if (i > 1)
out.print("</TH><TH ALIGN=\"LEFT\">");
out.print(metaData.getColumnLabel(i));
}
out.println("</TH></TR>");
while (result.next()) {
out.print("<TR><TD ALIGN=\"LEFT\">");
for (int i=1; i<=columnCount; i++) {
if (i > 1)
out.print("</TD><TD ALIGN=\"LEFT\">");
String s = result.getString(i);
if (result.wasNull())
out.print(" ");
else
out.print(s);
}
out.println("</TD></TR>");
}
out.println("</TABLE>");
result.close();
}
}