How to determine database type (name) for a given JDBC connection?

JDBCObject Oriented ProgrammingProgramming

One way to get the name of the underlying database you have connected with is by invoking the getDatabaseProductName() method of the DatabaseMetaData interface. This method returns the name of the underlying database in String format.

Therefore, to retrieve the name of your current database using Java code −

  • Retrieve the DatabaseMetaData object of the current Connection using the getMetaData() method.
//Retrieving the meta data object
DatabaseMetaData metaData = con.getMetaData();
  • Then, get the product name of the underlying database you have connected to using the getDatabaseProductName() method of the DatabaseMetaData interface as −
//retrieving the name of the database
String product_name = metaData.getDatabaseProductName();

Example

Following JDBC program establishes connection with the database, retrieves and prints the name of the underlying database.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseMetaData_getDatabaseProductName {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Retrieving the meta data object
      DatabaseMetaData metaData = con.getMetaData();
      //retrieving the name of the database
      String product_name = metaData.getDatabaseProductName();
      System.out.println("Name of the underlying database: "+product_name);
   }
}

Output

Connection established......
Name of the underlying database: MySQL
raja
Published on 03-Jul-2019 13:45:59
Advertisements