Java Reference
In-Depth Information
Example 17−2: GetDBInfo.java (continued)
// returned in a ResultSet, just like query results are.
if (table == null) {
System.out.println("Tables:");
ResultSet r = md.getTables("", "", "%", null);
while(r.next()) System.out.println("\t" + r.getString(3));
}
// Otherwise, list all columns of the specified table.
// Again, information about the columns is returned in a ResultSet
else {
System.out.println("Columns of " + table + ": ");
ResultSet r = md.getColumns("", "", table, "%");
while(r.next())
System.out.println("\t" + r.getString(4) + " : " +
r.getString(6));
}
}
// Print an error message if anything goes wrong.
catch (Exception e) {
System.err.println(e);
if (e instanceof SQLException)
System.err.println(((SQLException)e).getSQLState());
System.err.println("Usage: java GetDBInfo [-d <driver] " +
"[-s <dbserver>]\n" +
"\t[-u <username>] [-p <password>] <dbname>");
}
// Always remember to close the Connection object when we're done!
finally {
try { c.close(); } catch (Exception e) {}
}
}
}
Building a Database
Example 17-3 shows a program, MakeAPIDB , that takes a list of class names and
uses the Java Reflection API to build a database of those classes, the packages they
belong to, and all methods and fields defined by the classes. Example 17-4 shows
a program that uses the database created by this example.
MakeAPIDB uses the SQL CREATE TABLE statement to add three tables, named pack-
age , class , and member , to the database. The program then inserts data into those
tables using INSERT INTO statements. The program uses the same INSERT INTO
statements repeatedly, as it iterates though the list of class names. In this type of
situation, you can often increase the efficiency of your insertions if you use
PreparedStatement objects to execute the statements.
A prepared statement is essentially a blueprint for the statements you need to exe-
cute. When you send a SQL statement to the database, the database interprets the
SQL and creates a template for executing the statement. If you are sending the
same SQL statement repeatedly, only with different input parameters, the database
still has to interpret the SQL each time. On database platforms that support pre-
pared statements, you can eliminate this inefficiency by sending a prepared state-
ment to the database before you actually make any calls to the database. The
Search WWH ::




Custom Search