Java DatabaseMetaData getDatabaseMajorVersion() method with example

JDBCJava 8Object Oriented ProgrammingProgramming

The getDatabaseMajorVersion() method of the DatabaseMetaData interface returns the major version of the underlying database in integer format.

To get major version of the underlying database −

  • Make sure your database is up and running.

  • Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database.

  • Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables.

  • Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface.

  • Finally get the major version of the database using the getDatabaseMajorVersion() method of the DatabaseMetaData interface .

Example

Following JDBC program establishes connection with MySQL database, retrieves and, displays the major version of the underlying database.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseMetaData_getDatabaseMajorVersion {
   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 major version of the database
      int version = metaData.getDatabaseMajorVersion();
      System.out.println("Major version of the underlying database: "+version);
   }
}

Output

Connection established......
Major version of the underlying database: 5
raja
Published on 09-May-2019 14:46:36
Advertisements