Java Reference
In-Depth Information
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:Inventory");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData md = rs.getMetaData();
int nColumns = md.getColumnCount();
for(int i=1;i<=nColumns;i++){
System.out.print(md.getColumnLabel(i)+((i==nColumns)?"\n":"\t"));
}
while (rs.next()) {
for(int i=1;i<=nColumns;i++){
System.out.print(rs.getString(i)+((i==nColumns)?"\n":"\t"));
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
This example will print the ResultSet returned by a query to a file called "rs.txt". The command line to
run the example is:
java printResultSet jdbc:odbc:Contacts "SELECT * FROM CONTACT_INFO"
The output is tab delimited, so that it can easily be imported into MSWord. The example first retrieves
the column count for the ResultSet, then loops through the columns to get the column labels, which are
printed as the first line. It then loops through all the rows, retrieving the data in an inner loop. Table 10-4
shows the ResultSet output by the command line shown above.
Table 10-4: Formatting a ResultSet using ResultSetMetaData
FIRST_NAME
MI
LAST_NAME
STREET
CITY
STATE
ZIP
Michael
A
Corleone
123 Pine
New York
NY
10006
Fredo
X
Corleone
17 Main
New York
NY
10007
Sonny
A
Corleone
123 Walnut
Newark
NJ
12346
Francis
X
Corleone
17 Main
New York
NY
10005
Vito
G
Corleone
23 Oak St
Newark
NJ
12345
Tom
B
Hagen
37 Chestnut
Newark
NJ
12345
Kay
K
Adams
109 Maple
Newark
NJ
12345
Francis
F
Coppola
123 Sunset
Hollywood
CA
23456
Mario
S
Puzo
124 Vine
Hollywood
CA
23456
Michael
J
Fox
109 Sepulveda
LA
CA
91234
James
A
Caan
113 Sunset
Hollywood
CA
92333
Search WWH ::




Custom Search