Java Reference
In-Depth Information
Example 17−1: ExecuteSQL.java (continued)
for(int i = 0; i < numcols; i++) {
int pos = colpos[i] + 1 + (colwidths[i]-labels[i].length())/2;
overwrite(line, pos, labels[i]);
overwrite(line, colpos[i] + colwidths[i], " |");
}
// Then output the line of column labels and another divider
out.println(line);
out.println(divider);
// Now, output the table data. Loop through the ResultSet, using
// the next() method to get the rows one at a time. Obtain the
// value of each column with getObject(), and output it, much as
// we did for the column labels above.
while(rs.next()) {
line = new StringBuffer(blankline.toString());
line.setCharAt(0, '|');
for(int i = 0; i < numcols; i++) {
Object value = rs.getObject(i+1);
if (value != null)
overwrite(line, colpos[i] + 1, value.toString().trim());
overwrite(line, colpos[i] + colwidths[i], " |");
}
out.println(line);
}
// Finally, end the table with one last divider line.
out.println(divider);
out.flush();
}
/** This utility method is used when printing the table of results */
static void overwrite(StringBuffer b, int pos, String s) {
int slen = s.length(); // String length
int blen = b.length(); // Buffer length
if (pos+slen > blen) slen = blen-pos; // Does it fit?
for(int i = 0; i < slen; i++)
// Copy string into buffer
b.setCharAt(pos+i, s.charAt(i));
}
}
Using Database Metadata
Sometimes, in addition to querying and updating the data in a database, you also
want to retrieve information about the database itself and its contents. This infor-
mation is called metadata . The DatabaseMetaData interface allows you to retrieve
this kind of information. You can obtain an object that implements this interface
by calling the getMetaData() method of the Connection object, as shown in Exam-
ple 17-2.
After GetDBInfo opens a database Connection and obtains a DatabaseMetaData
object, it displays some general information about the database server and JDBC
driver. Then, if the user just specified a database name on the command line, the
program lists all the tables in that database. If the user specified a database name
Search WWH ::




Custom Search