Database and Table Metadata through JDBC

Until now I queried the Information schema for the meta data, such as fields of a table, constraints, keys… The Information Schema varies with the database product and must be implemented specifically for one product. But you don’t have to go that route, you can use the meta data within the java.sql package to gain the information.
The retrieval of the meta data for a table is fairly easy. You construct an SQL on your table and execute it. From the resulting ResultSet you can retrieve the MetaDataResultSet which contains among other stuff the field name, the field type, nullable and autoincrement:

ResultSet set =stmt.executeQuery(sql);
ResultSetMetaData resultMeta = set.getMetaData();
for (int i=1;i< =resultMeta.getColumnCount();i++){ String fieldName = resultMeta.getColumnName(i); int type = resultMeta.getColumnType(i); // java.sql.Types Class _fieldType = convertType(type);
boolean nullable = resultMeta.isNullable(i)!=java.sql.ResultSetMetaData.columnNoNulls;
boolean isAutoincrement = resultMeta.isAutoIncrement(i);
System.out.printf("Field: %s, %s, nullable %b, autoincrement %b%n",fieldName,_fieldType.getName(),nullable,isAutoincrement);
}

The type is specified as an integer constant in java.sql.Types.
Information on the constraints can be retrieved from the DatabaseMetaData which can bee retrieved from the connection. Of interest are especially 3 methods:

  • getPrimaryKeys(catalog,schema,table) to retrieve a ResultSet that contains; one entry for each column for each primary key.
  • getIndexInfo(catalog,schema,table,unique,false) to retrieve indices unique and otherwise. You retrieve a ResultSet that contains one entry for each column for each index. If unique is false the result contains unique and non unique keys.
  • getExportedKeys(catalog,schema,table) to retrieve a ResultSet that contains all foreign keys; one entry for each column for each key.

A full code sample can be downloaded here. To run it you have to supply specific values for your database as well as download this herlper class.

Schreibe einen Kommentar