【问题标题】:Easiest way to obtain database metadata in Java?在 Java 中获取数据库元数据的最简单方法是什么?
【发布时间】:2010-11-02 08:52:39
【问题描述】:

我对@9​​87654321@ 界面很熟悉,但我发现它使用起来很笨拙。例如,为了找出表名,您必须调用getTables 并循环通过返回的ResultSet,使用众所周知的文字作为列名。

有没有更简单的方法来获取数据库元数据?

【问题讨论】:

    标签: java database metadata ddlutils


    【解决方案1】:

    使用DdlUtils 可以轻松完成:

    import javax.sql.DataSource;
    import org.apache.ddlutils.Platform;
    import org.apache.ddlutils.PlatformFactory;
    import org.apache.ddlutils.model.Database;
    import org.apache.ddlutils.platform.hsqldb.HsqlDbPlatform;
    
    public void readMetaData(final DataSource dataSource) {
      final Platform platform = PlatformFactory.createNewPlatformInstance(dataSource);
      final Database database = platform.readModelFromDatabase("someName");
      // Inspect the database as required; has objects like Table/Column/etc.
    }
    

    【讨论】:

      【解决方案2】:

      看看 SchemaCrawler(免费和开源),这是另一个为此目的而设计的 API。一些示例 SchemaCrawler 代码:

          // Create the options
      final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
      // Set what details are required in the schema - this affects the
      // time taken to crawl the schema
      options.setSchemaInfoLevel(SchemaInfoLevel.standard());
      options.setShowStoredProcedures(false);
      // Sorting options
      options.setAlphabeticalSortForTableColumns(true);
      
      // Get the schema definition 
      // (the database connection is managed outside of this code snippet)
      final Database database = SchemaCrawlerUtility.getDatabase(connection, options);
      
      for (final Catalog catalog: database.getCatalogs())
      {
        for (final Schema schema: catalog.getSchemas())
        {
          System.out.println(schema);
          for (final Table table: schema.getTables())
          {
            System.out.print("o--> " + table);
            if (table instanceof View)
            {
              System.out.println(" (VIEW)");
            }
            else
            {
              System.out.println();
            }
      
            for (final Column column: table.getColumns())
            {
              System.out.println("     o--> " + column + " (" + column.getType()
                                 + ")");
            }
          }
        }
      }
      

      http://schemacrawler.sourceforge.net/

      【讨论】:

      • 您需要自己关闭连接还是使用 getDatabase() 方法为您完成此操作?
      • @AndrewSwan - SchemaCrawler 不会为您关闭连接。你需要自己关闭它。
      • 在这种情况下,您可能想更新您的示例,以便它在 finally 块中关闭连接?
      • 安德鲁,我添加了一条评论来表明这一点。我认为应该尽量减少 stackoverflow 示例来说明答案,而不是考虑最佳实践的完整生产代码。
      • @SualehFatehi 最新版本的 Schematic Crawler 是否支持 Java 6?我在常见问题解答中只看到过 Java 7。对于 Java 6,我应该使用哪个版本?请告诉我。
      猜你喜欢
      • 2011-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      相关资源
      最近更新 更多