Sun Java Solaris Communities My SDN Account Join SDN
 
Tutorials & Code Camps

Java Technology Fundamentals Solution

 

New-to-Java Programming Center
Technology Fundamentals

For June's Challenge Program MetaTest:

  • Create a program that connects to your database
  • Display information about the database and driver used to make the connection.

Methods to access database information is available through the DatabaseMetaData associated with the connection.

A possible solution to the June 2002 Java Technology Fundamentals Program Challenge, MetaTest:

import java.sql.*;

public class MetaTest {

   // String defining database connection

   static final String dbURI = "jdbc:mysql:///test";

   public static void main(String args[])
       throws ClassNotFoundException, SQLException {

     // Connection reference
     Connection conn = null;

     try {

       // Load database driver
       Class.forName("org.gjt.mm.mysql.Driver");

       // Make connection
       conn = DriverManager.getConnection(dbURI);

       // Get the database meta data
       DatabaseMetaData dmd = conn.getMetaData();

       // Display information about the database 
       // product and driver

       if (dmd == null) {

         System.out.println("Database meta data not available");

       } else {

         System.out.println(
           "Database Product Name   : " +
           dmd.getDatabaseProductName());
         System.out.println(
           "Database Product Version: " +
           dmd.getDatabaseProductVersion());
         System.out.println(
           "Database Driver Name    : " +
           dmd.getDriverName());
         System.out.println(
           "Database Driver Version : " +
           dmd.getDriverVersion());
       }

     } finally {

       // Close connection

       if (conn != null) {
         try {
           conn.close();
         } catch (SQLException sqlEx) {
           // ignore
         }
       }
     }
   }
}

Have a question about programming? Use Java Online Support.