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

And*_*wan 9 java database metadata ddlutils

我对java.sql.DatabaseMetaData界面很熟悉,但我发现它非常笨重.例如,为了找出表名,您必须使用众所周知的文字作为列名来调用getTables并循环返回ResultSet.

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

And*_*wan 11

使用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.
}
Run Code Online (Sandbox Code Playgroud)


Sua*_*ehi 6

看一下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()
                           + ")");
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

http://schemacrawler.sourceforge.net/

  • 安德鲁,我添加了一条评论来表明这一点.我认为stackoverflow示例应保持最小以说明答案,而不是将最佳实践考虑在内的完整生产代码. (4认同)