Saturday 4 July 2020

How to Use DatabaseMetaData to Learn Database Information in java programming language

How to Use DatabaseMetaData to Learn Database Information in java programming language

In the following post you can learn how to retriev data at interface of application by using java and by method  getMetaData method of the Connection class is used to return a DatabaseMetadata object in java , and then various methods of the DatabaseMetaData object are used to display information about the driver, driver version, database name, and database version:

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

public class JDBCDatabaseMetaData {

    private static final String DBURL = 
          "jdbc:mysql://localhost:3306/mydb?user=usr&password=sql" +
          "&useUnicode=true&characterEncoding=UTF-8";
    private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
  
    static {
        try {
            Class.forName(DBDRIVER).newInstance();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private static Connection getConnection() 
    {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(DBURL);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void main(String[] args) {
      Connection con = getConnection();
      try {
        DatabaseMetaData dbmd = con.getMetaData();
        System.out.println("dbmd:driver version = "
                  + dbmd.getDriverVersion());
        System.out.println("dbmd:driver name = " 
                  + dbmd.getDriverName());
        System.out.println("db name = " 
                  + dbmd.getDatabaseProductName());
        System.out.println("db ver = " 
                  + dbmd.getDatabaseProductVersion());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

}

0 comments:

Post a Comment