Sunday, 13 July 2014

JDBC DatabaseMetadata Demo

Enjoying Java & Database Tutorials?

Subscribe to Ram N Java on YouTube for beginner-friendly coding lessons and hands-on demos!

🔔 Subscribe to Channel

How to Use DatabaseMetaData in Java JDBC

When building dynamic or database-agnostic applications, you often need to inspect the database system itself—such as checking the database product name, version, supported SQL features, or listing available tables. In Java, JDBC (Java Database Connectivity) provides the DatabaseMetaData interface to extract comprehensive information about the connected database.

What Can You Check with DatabaseMetaData?

The DatabaseMetaData interface provides dozens of methods to query server capabilities and schema details:

  • Database & Driver Details: Methods like getDatabaseProductName(), getDatabaseProductVersion(), getDriverName(), and getDriverVersion().
  • Feature Support: Determine whether transactions, batch updates, savepoints, or specific SQL syntax are supported using methods like supportsTransactions() or supportsBatchUpdates().
  • Catalog & Schema Information: Inspect tables, columns, primary keys, and foreign keys via getTables(), getColumns(), and getPrimaryKeys().

Step-by-Step Java Implementation

Follow these standard steps to obtain and use DatabaseMetaData in JDBC:

  1. Establish Connection: Connect to your target database using DriverManager.getConnection().
  2. Obtain Metadata Object: Call connection.getMetaData() to retrieve the DatabaseMetaData instance.
  3. Query Information: Invoke metadata methods to print database names, versions, or supported features to the console.
  4. Explore Tables & Columns: Use methods like getTables() which return a ResultSet you can iterate over.
  5. Clean Up: Safely release resources using try-with-resources.

Watch More JDBC Tutorials


Click here to watch in Youtube : https://www.youtube.com/watch?v=9thq3gQoFtY

Click the below Image to Enlarge

JDBCDatabaseMetaDataDemo Project Dir Structure

JDBCDatabaseMetaDataDemo.java
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDatabaseMetaDataDemo
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

    public static void main(String[] args)
    {

        JDBCDatabaseMetaDataDemo jdbcDatabaseMetaDataDemo = new JDBCDatabaseMetaDataDemo();
        jdbcDatabaseMetaDataDemo.getDatabaseMetadataInformation();

    }

    private void getDatabaseMetadataInformation()
    {
        Connection connection = null;
        Statement stmt = null;
        try
        {
            /*
             * Register the JDBC driver in DriverManager
             */

            Class.forName(JDBC_DRIVER);

            /*
             * Establish connection to the Database using DriverManager
             */

            connection = DriverManager
                    .getConnection(DB_URL, USERNAME, PASSWORD);

            DatabaseMetaData dbmd = connection.getMetaData();

            System.out.println("Driver Name: " + dbmd.getDriverName());
            System.out.println("Driver Version: " + dbmd.getDriverVersion());
            System.out.println("UserName: " + dbmd.getUserName());
            System.out.println("Database Product Name: "
                    + dbmd.getDatabaseProductName());
            System.out.println("Database Product Version: "
                    + dbmd.getDatabaseProductVersion());

            /*
             * Get all the table names from the world schema
             */
            System.out.println();
            System.out
                    .println("------------------Tables-----------------------------");

            String table[] =
                {
                    "TABLE"
                };
            ResultSet rs = dbmd.getTables(null, null, null, table);

            while (rs.next())
            {
                System.out.println(rs.getString(3));
            }

            rs.close();
            connection.close();
        }
        catch (SQLException se)
        {
            /*
             * Handle errors for JDBC
             */
            se.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            /*
             * Handle errors for Class.forName
             */
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if (stmt != null)
                {
                    stmt.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
            try
            {
                if (connection != null)
                {
                    connection.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
        }

    }

}

Output
Driver Name: MySQL Connector Java
Driver Version: mysql-connector-java-5.1.31 ( Revision: alexander.soklakov@oracle.com-20140520065950-groqzzbvxprqdmnz )
UserName: root@localhost
Database Product Name: MySQL
Database Product Version: 5.6.19

------------------Tables-----------------------------
city
country
countrylanguage

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCDatabaseMetaDataDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCDatabaseMetaDataDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials