9

私はjava.sql.DatabaseMetaDataインターフェースに精通していますが、使用するのはかなり不格好です。たとえば、テーブル名を見つけるには、列名としてよく知られているリテラルを使用しgetTablesて、返されたを呼び出してループする必要があります。ResultSet

データベースメタデータを取得する簡単な方法はありますか?

4

2 に答える 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.
}
于 2009-06-12T04:36:50.927 に答える
6

この目的のために設計された別のAPIであるSchemaCrawler(無料のオープンソース)を見てください。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/

于 2009-06-16T19:12:44.990 に答える