Working with Metadata

Metadata is data about data, and in the context of our study of JDBC, it's the information provided about the properties of data sources and result sets. Querying metadata is very powerful in creating tools for database manipulation and sophisticated database applications.

To find information about the connected database, we use the method getMetaData() of the Connection object to retrieve a DatabaseMetaData object. You can get information about schemas, tables, and properties of each table. The following sample queries database metadata to display all the table names and properties of each table in the schema "APP":

// Finding MetaData about database
DatabaseMetaData dbmd = conn.getMetaData();
String[] types = {"TABLE"};
System.out.println("Database Table Names for the Schema "APP")
rs = dbmd.getTables(null, "APP", null, types);
while (rs.next()){
    String tableName = rset.getString("TABLE_NAME");
    System.out.println("Table Name: " + tableName);
    ResultSet rsc = dbmd.getColumns(null,null,tableName,"%");
    System.out.println("Column Name" + "    Data Type" + " Width");
    while (rsc.next()){
      System.out.println(rsc.getString("COLUMN_NAME") + "..." +
                         rsc.getString("TYPE_NAME") + "..." +
                         rsc.getInt("COLUMN_SIZE"));
    }
}

When sending a SELECT statement to the database, you receive a ResultSet that holds the records to satisfy your criteria. To find metadata information about a ResultSet object, use the getMetaData() method of the ResultSet interface. This metadata will be captured and retrieved by getMetaData() into a ResultSetMetaData object. Such metadata of a ResultSet is the number of columns and the database properties of each column, such as its name, type, width, and precision. An example of retrieving a ResultSetMetaData object about a ResultSet is the following:

// Finding MetaData about result set
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");
ResultSetMetaData rsmd = rs.getMetaData();
int cn = rsmd.getColumnCount();
// Printing column information
for (int i=1; i<= cn ; i++) {
      if (i > 1) { System.out.print(", "); }
      System.out.print(rsmd.getColumnLabel(i));
}
System.out.print("")
// Printing the data
while (rs.next ()) {
       for (int i=1; i<=cn; i++) {
         if (i > 1) { System.out.print(", "); }
           System.out.print(rs.getString(i));
       }
       System.out.println("");
}

By combining ResultSetMetaData and DatabaseMetaData, toolmakers can build very powerful database interactive tools to query and schema objects and data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.80.209