JDBC API 4.2(十):DatabaseMetaData 接口源碼分析

1、簡介

DatabaseMetaData 接口提供了獲取數據庫元數據的方法,例如數據庫名稱,數據庫版本,驅動程序名稱,表總數,視圖總數等。

該接口由驅動程序供應商實現,以使用戶瞭解數據庫管理系統(DBMS)的功能以及與之結合使用的基於JDBC技術的驅動程序。

不同的DBMS通常支持不同的功能,以不同的方式實現功能以及使用不同的數據類型。 另外,驅動程序可以在DBMS提供的功能之上實現功能。 該接口中方法返回的信息適用於特定驅動程序和特定DBMS協同工作的功能。

一些 DatabaseMetaData 方法採用的參數是字符串模式。 這些參數都具有諸如fooPattern之類的名稱。 在模式字符串中,“%”表示匹配任何0個或多個字符的子字符串,“ _”表示匹配任何一個字符。 僅返回與搜索模式匹配的元數據條目。 如果將搜索模式參數設置爲null,則將從搜索中刪除該參數的條件。

2、常用方法

方法描述
String getDriverName() throws SQLException返回 JDBC driver 名稱
String getDriverVersion() throws SQLException返回 JDBC driver 版本
String getUserName()throws SQLException返回數據庫用戶名
String getDatabaseProductName() throws SQLException返回數據庫產品名稱
String getDatabaseProductVersion()throws SQLException 返回數據庫產品版本
ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException檢索滿足指定條件的可用表的描述。

3、示例

public class DatabaseMetaDataDemo {
    public static void main(String[] args) {
        databaseInfo();
    }

    private static void databaseInfo() {      
        try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/lkf_db?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT", "root", "root");) {
            DatabaseMetaData dbmd = connection.getMetaData();
            System.out.println("Driver Name: " + dbmd.getDriverName());
            System.out.println("Driver Version: " + dbmd.getDriverVersion());
            System.out.println("UserName: " + dbmd.getUserName());
            System.out.println("Database Product Name: " + dbmd.getDatabaseProductName());
            System.out.println("Database Product Version: " + dbmd.getDatabaseProductVersion());
        } catch (SQLException e) {
            printSQLException(e);
        }
    }

    public static void printSQLException(SQLException ex) {
        for (Throwable e: ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}

輸出:

Driver Name: MySQL Connector/J
Driver Version: mysql-connector-java-8.0.15 (Revision: 79a4336f140499bd22dd07f02b708e163844e3d5)
UserName: root@localhost
Database Product Name: MySQL
Database Product Version: 8.0.17
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章