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 information 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 Example 18-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 and a table name, however, the program lists the name and data type of each column in that table.

An interesting feature of this GetDBInfo program is how it obtains the parameters needed to connect to the database. The example operates on the premise that at any given site, it is typically used to connect to the same database server, using the same database driver, and may also be used with the same database username and password. So, instead of requiring the user to type all this cumbersome information on the command line each time the program is run, the program reads default values from a file named DB.props that is stored in the same directory as the GetDBInfo.class file. In order to run Example 18-2, you have to create an appropriate ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.