- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java DatabaseMetaData getCatalogs() 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 getCatalogs() method of the DatabaseMetaData interface returns the name of the underlying database in String format.
To get the list of catalogs of the database at an instance −
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 database catalog using the getCatalogs() method of the DatabaseMetaData interface .
Example
Let us create 6 in databases in MySQL using CREATE statements as shown below −
Create database mydatabase; Create database exampledatabase; Create database sampledb; Create database students; Create database testdb; Create database details;
Following JDBC program establishes connection with MySQL database, retrieves and, displays the list of catalogs in it at the instance.
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class DatabaseMetaData_getCatalogs { 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(); //Returns the name of the database ResultSet rs = metaData.getCatalogs(); System.out.println("List of the catalogs in the database"); while(rs.next()) { System.out.println(rs.getString(1)); } } }
Output
Connection established...... List of the catalogs in the database information_schema details exampledatabase mydatabase mysql performance_schema sampledb students sys testdb