The public Java interface called java.sql.DatabaseMetaData defines methods that allow the JDBC developer to obtain detailed pieces of information about the database as a whole. There are many, many methods contained within this interface. Because it is an interface, there must be a concrete class that implements the interface so that the methods can be called. This concrete class is the Connection class itself. You can call the getMetaData method on a Connection object and obtain the metadata for the database that the Connection is connected to. After you have the metadata, you can query for just about anything that you want to know about the database. The example in Listing 26.15 shows some of the information that can be obtained through the DatabaseMetaData interface. Listing 26.15 Source Code for MetaDataExample.javaimport java.sql.*; public class MetaDataExample { // Default Constructor public MetaDataExample() { super(); } // Just a convenience print method public void print( String txt ) { System.out.println( txt ); } // Main method for this example public static void main(String[] args) { try { // Acquire a connection from the DatabaseManager Connection conn = DatabaseManager.getConnection(); MetaDataExample example = new MetaDataExample(); // Get the MetaData DatabaseMetaData metaData = conn.getMetaData(); // Get driver information example.print( "Driver Information" ); example.print( metaData.getDriverName() ); example.print( metaData.getDriverVersion() ); example.print( "" ); // Get schema information example.print( "Schemas" ); ResultSet schemas = metaData.getSchemas(); while( schemas.next() ) { example.print( schemas.getString(1) ); } example.print( "" ); // Get table information example.print( "Tables" ); ResultSet tables = metaData.getTables( "", "", "", null ); while( tables.next() ) { example.print( tables.getString(3) ); } // Always close the open resources conn.close(); } catch( Exception ex ) { ex.printStackTrace(); } } } Listing 26.16 Output from MetaDataExample.javaC:\jdk1.3se_book\classes>java MetaDataExample Driver Information oracle.lite.poljdbc.POLJDBCDriver OLite 4.0 Schemas SYSTEM SCOTT Tables BONUS CUSTOMER DEPT DUMMY EMP INVENTORY ITEM ORD PRICE PRODUCT PRODUCT_COMPOSITION SALARYHISTORY SALGRADE T_EMP SALES C:\jdk1.3se_book\classes> Note There might be some variation in your output based on the database vendor and version. You might also have to use a name /string pattern and null for the other parameters in the getTables() method in Listing 26.15. Check your driver and vendor documentation for more information on the variations. Again, there are so many methods that you can use to obtain information about the database that they can't all be mentioned here. You can review the documentation for the DatabaseMetaData interface for additional details. |