hen developers connect to a database with JDBC, they receive a plethora of information about the database and any ResultSet objects that they might create using the database connection. This data, provided as database metadata, has been around since JDBC 1.0 and it can take different forms.
This article explores the information JDBC metadata provides by demonstrating how to create an IBM DB2 database and then invasively peek into it via Java. It focuses on two forms of metadata: one describing a given database connection, the other describing a ResultSet object. Each of these forms will have an associated Java interface: the java.sql.DatabaseMetaData interface, which provides information about the database connection, and the ResultMetaData interface, which provides information about the ResultSet object.
Some database veterans may opt for querying a database server's system catalog tables to retrieve some of the information that they can discover via the DatabaseMetaData and ResultSetMetaData interfaces. However, this option ties them to a specific database, as each database server has a different set of system catalog tables. JDBC enables a database-agnostic approach to gathering database metadata information.
Set Up a DB2 Laboratory
As this article uses IBM DB2 Universal Database as the underlying database, your first step is downloading a trial version of IBM DB2 Universal Database Version 8.1. Of course, the methodologies for acquiring information via the DatabaseMetaData and ResultSetMetaData interfaces apply for any other JDBC-compliant database you might use.
Begin by creating a DB2 database using the DB2 Command Line Processor. Create a database named EMPDB to store employee data:
db2 => create db EMPDB
Next, connect to your database (assuming you have a user named db2admin with a password of db2admin):
db2 => connect to EMPDB user db2admin using db2admin
Next, create a table called EMPLOYEE, which will store some information about your imaginary employees:
db2 => create table EMPLOYEE(SSN integer not null primary key,
FIRSTNAME varchar(30) not null, LASTNAME varchar(30) not null,
SALARY decimal (8,2) NOT NULL)
Now, populate your EMPLOYEE table with some sample records:
db2 => insert into EMPLOYEE values (123456789,'James','Smith',79345.00)
db2 => insert into EMPLOYEE values (123456790,'Bob','Jeffries',65321.23)
db2 => insert into EMPLOYEE values (123456791,'Amy','Keppler',49998.56)