2009-06-12 46 views
9

Tôi quen thuộc với giao diện java.sql.DatabaseMetaData, nhưng tôi thấy nó khá khó sử dụng. Ví dụ: để tìm ra tên bảng, bạn phải gọi getTables và lặp lại thông qua số ResultSet trả về, sử dụng các chữ nổi tiếng làm tên cột.Cách dễ nhất để lấy siêu dữ liệu cơ sở dữ liệu trong Java?

Có cách nào dễ dàng hơn để lấy siêu dữ liệu của cơ sở dữ liệu không?

Trả lời

11

Nó dễ dàng thực hiện bằng 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

Hãy xem SchemaCrawler (miễn phí và mã nguồn mở), mà là một API được thiết kế cho mục đích này. Một số mã SchemaCrawler mẫu:

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

+0

Bạn có cần để đóng kết nối cho bản thân hoặc không phương pháp() getDatabase làm điều đó cho bạn? –

+0

@AndrewSwan - SchemaCrawler sẽ không đóng kết nối cho bạn. Bạn cần tự đóng nó lại. –

+0

Trong trường hợp đó bạn có thể muốn cập nhật ví dụ của bạn để nó đóng kết nối trong một khối cuối cùng? –

Các vấn đề liên quan