JDBC Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 2.11

Listing All Databases - getCatalogs()

This section describes how to get a list of all databases on the SQL Server through the DatabaseMetaData object.

If you want to list all databases on the SQL Server, you can use the DatabaseMetaData method: getCatalogs(). It returns all databases in a ResultSet object with one field, TABLE_CAT, containing the database name.

Note that a JDBC catalog is mapped to SQL Server database.

The tutorial Java program below shows you how to list all databases on the SQL Server:

/**
 * ListDatabases.java
 * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
 */
import java.sql.*;
public class ListDatabases {
  public static void main(String [] args) {
    Connection con = null;
    try {

      Class.forName(
        "com.microsoft.sqlserver.jdbc.SQLServerDriver");
      con = DriverManager.getConnection(
          "jdbc:sqlserver://localhost:1269;"
        + "user=sa;password=HerongYang");

      DatabaseMetaData meta = con.getMetaData();
      ResultSet res = meta.getCatalogs();
      System.out.println("List of databases: "); 
      while (res.next()) {
         System.out.println("   "
           +res.getString("TABLE_CAT"));
      }
      res.close();

      con.close();
    } catch (java.lang.ClassNotFoundException e) {
      System.err.println("ClassNotFoundException: "
        +e.getMessage());
    } catch (SQLException e) {
      System.err.println("SQLException: "
        +e.getMessage());
    }
  }
}

Here is the output of the program:

List of databases:
   AdventureWorksLT
   master
   model
   msdb
   tempdb

Sections in This Chapter

Commonly Used DatabaseMetaData Methods

Getting Database Server and Driver Info

Listing All Databases - getCatalogs()

Listing All Schemas - getSchemas()

Listing All Tables - getTables()

Listing All Culumns - getColumns()

Listing All Stored Procedures - getProcedures()

Dr. Herong Yang, updated in 2007
Listing All Databases - getCatalogs()