University of Cincinnati logo and link  
Metadata Example
 
  UC ingot Here's the source for our Metadata example.
  • When you do the column count for loop, be sure to get old school about it.  Columns in SQL start with 1, so we have to start our increment variable at 1 and use the <= operator instead of the < operator.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
 <META http-equiv="Expires" content="0" > </META>
 <title>Insert Data</title>
</HEAD>
<BODY>

<P align="center">
 <font size="7">
Metadata
 </font>
</P>
 
 

<%@ page import = "java.sql.*" %> 

<%
 

 // Connection info. 
 
 Class.forName("com.mysql.jdbc.Driver").newInstance();
 
 java.sql.Connection conn;
 
 conn = DriverManager.getConnection("jdbc:mysql://localhost/students");

 Statement stmt = conn.createStatement();

 // Get the metadata object.
 DatabaseMetaData meta = conn.getMetaData();

 // get the name and version of the database; print this out.
 String dbName = meta.getDatabaseProductName();
 String dbVersion = meta.getDatabaseProductVersion();

 out.print("<p>Database Name, Version: " + dbName + " " + dbVersion + "</p>");

 // get and print driver info
 String dbDriver = meta.getDriverName();

 out.print("<p> Using " + dbDriver + " </p>");

 // find out if the database wears the union label.
 boolean blnUnion = meta.supportsUnion();
 if (blnUnion) {
  out.print("<p>This database suppors unions.</p>");
 } else {
  out.print("<p>This database does not support unions.</p>");
 }

 // Get the table names.  Iterate through them and print them out.
 ResultSet rsTables = meta.getTables(null, null, null, new String[] { "TABLE" });
 
 int tableNum = 0;

 out.print("<TABLE>");
 while (rsTables.next()) {
  tableNum++;
  out.print("<tr><td>Table Number </td><td>" + tableNum + "</td><td> Name: </td><td>" + rsTables.getString(3) + "</td></tr>");
 }
 out.print("</TABLE>");

 // table for the results.
 out.print("<table border =1>");

 // Do the select.

 ResultSet rs = stmt.executeQuery("Select * from students, colleges where students.CollegeID = colleges.CollegeID");

 // Get the metadata from this result set.
 ResultSetMetaData rsmd = rs.getMetaData();
 
 // Print the column labels dynamically.
 out.print("<tr>");
 out.print("<td>Record Number</td>");
 for (int colNum = 1; colNum <= rsmd.getColumnCount(); colNum++) {
  out.print("<td>" + rsmd.getColumnLabel(colNum) + "</td>");  

 }
 out.print("</tr>");

 int recordNo = 0;
 

 // Go through the results.  Print.
 while(rs.next()) {
  // increment, print the record number
  recordNo++;
  out.print("<tr><td>" + recordNo + "</td>");

  // print the column values dynamically.
  for (int colNum = 1; colNum <= rsmd.getColumnCount(); colNum++) {
   out.print("<td>" + rs.getString(colNum) + "</td>");
//   out.print("Column No: " + colNum);
  }
  out.print("</tr>");
 }
 out.print("</table>");
%>
 

Database connection complete.

</BODY>
</HTML>
 

 Transactions