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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值