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

9
我熟悉java.sql.DatabaseMetaData接口,但我发现它使用起来很笨拙。例如,为了找出表名,您必须调用getTables并循环遍历返回的ResultSet,使用众所周知的字面量作为列名。
有没有更简单的方法来获取数据库元数据?
2个回答

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.
}

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()
                           + ")");
      }
    }
  }
}

http://schemacrawler.sourceforge.net/


你需要自己关闭连接还是getDatabase()方法会为你关闭连接? - Andrew Swan
@AndrewSwan - SchemaCrawler 不会为您关闭连接。 您需要自行关闭它。 - Sualeh Fatehi
在这种情况下,您可能希望更新您的示例以便在finally块中关闭连接? - Andrew Swan
4
安德鲁,我已经添加了一条评论来说明这一点。我认为stackoverflow的例子应该尽量简洁,以便说明答案,而不是完整的生产代码,需要考虑最佳实践。 - Sualeh Fatehi
感谢您的快速回复。 - phoenix
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接