Java Connection getCatalog() method with example


In general, a catalog is a directory which holds information about data sets, file or, a database. Whereas in a database catalog holds the list of all the databases, base tables, views (virtual tables), synonyms, value ranges, indexes, users, and user groups.

The getCatalog() method of the Connection interface returns the name of the current catalog/database, of the current connection object.

This method returns a Sting value representing the name of the catalog. It returns null if there is no catalog.

To get the catalog name −

Register the driver using the registerDriver() method of the DriverManager class as −

//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

Get the connection using the getConnection() method of the DriverManager class as −

//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");

Retrieve the connection objects catalog name using the getCatalog() method as −

//Retrieving the current catalog name
String catalogName = con.getCatalog();

Let us create a database with name mydatabase in MySQL using CREATE statement as shown below.

create database mydatabase;

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

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_getCatalog {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Setting the auto commit false
      con.setAutoCommit(false);
      //Retrieving the current catalog name
      String catalogName = con.getCatalog();
      System.out.println("Current catalog name is: "+catalogName);
   }
}

Output

Connection established......
Current catalog name is: mydatabase
raja
Published on 15-May-2019 15:13:52
Advertisements