代码之家  ›  专栏  ›  技术社区  ›  Andrew Swan

在Java中获取数据库元数据的最简单方法?

  •  9
  • Andrew Swan  · 技术社区  · 17 年前

    我熟悉 java.sql.DatabaseMetaData 接口,但我发现它使用起来相当笨拙。例如,为了找出表名,必须调用 getTables 然后循环返回 ResultSet ,使用已知的文本作为列名称。

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

    2 回复  |  直到 9 年前
        1
  •  11
  •   Andrew Swan    17 年前

    很容易用 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
  •  6
  •   Sualeh Fatehi    14 年前

    看看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/