Easiest way to obtain database metadata in Java?

被刻印的时光 ゝ 提交于 2019-11-27 02:21:07

问题


I'm familiar with the java.sql.DatabaseMetaData interface, but I find it quite clunky to use. For example, in order to find out the table names, you have to call getTables and loop through the returned ResultSet, using well-known literals as the column names.

Is there an easier way to obtain database metadata?


回答1:


It's easily done using 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:


Take a look at SchemaCrawler (free and open source), which is another API designed for this purpose. Some sample SchemaCrawler code:

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



来源:https://stackoverflow.com/questions/985010/easiest-way-to-obtain-database-metadata-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!