帶範例的 Java Connection getCatalog() 方法


通常,目錄是包含有關資料集、檔案或資料庫資訊的目錄。而在資料庫中,目錄包含所有資料庫、基本表、檢視(虛擬表)、同義詞、值範圍、索引、使用者和使用者組的列表。

Connection 介面的 getCatalog() 方法返回當前連線物件中當前目錄/資料庫的名稱。

該方法返回一個表示該目錄名稱的 Sting 值。如果不存在目錄,則返回 null。

獲取目錄名稱 −

使用 DriverManager 類的 registerDriver() 方法註冊該驅動程式,如下所示 −

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

使用 DriverManager 類 的 getConnection() 方法獲取連線,如下所示 −

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

使用 getCatalog() 方法檢索連線物件的目錄名稱,如下所示 −

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

讓我們使用 CREATE 語句在 MySQL 中建立一個名為 mydatabase 的資料庫,如下所示。

create database mydatabase;

以下 JDBC 程式建立與 MySQL 資料庫的連線,檢索並顯示底層目錄的名稱。

範例

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:///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);
   }
}

輸出

Connection established......
Current catalog name is: mydatabase

更新時間:2019 年 7 月 30 日

871 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.