我對java.sql.DatabaseMetaData
界面很熟悉,但是我覺得它的使用非常笨重。例如,爲了找出表名,你必須調用getTables
並通過返回的ResultSet
循環,使用衆所周知的文字作爲列名。在Java中獲取數據庫元數據的最簡單方法是什麼?
是否有更簡單的方法來獲取數據庫元數據?
我對java.sql.DatabaseMetaData
界面很熟悉,但是我覺得它的使用非常笨重。例如,爲了找出表名,你必須調用getTables
並通過返回的ResultSet
循環,使用衆所周知的文字作爲列名。在Java中獲取數據庫元數據的最簡單方法是什麼?
是否有更簡單的方法來獲取數據庫元數據?
它使用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.
}
看看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()
+ ")");
}
}
}
}
你需要自己關閉連接或沒有的getDatabase()方法爲你做的? – 2012-02-27 04:27:19