2009-06-12 17 views
9

मैं java.sql.DatabaseMetaData इंटरफ़ेस से परिचित हूं, लेकिन मुझे इसका उपयोग करने के लिए काफी कठोर लगता है। उदाहरण के लिए, तालिका नामों को जानने के लिए, आपको getTables पर कॉल करना होगा और कॉलम नामों के रूप में जाने-माने साहित्यिक का उपयोग करके ResultSet पर लौटाना होगा।जावा में डेटाबेस मेटाडेटा प्राप्त करने का सबसे आसान तरीका?

क्या डेटाबेस मेटाडेटा प्राप्त करने का कोई आसान तरीका है?

उत्तर

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 (स्वतंत्र और खुला स्रोत) है, जो इस उद्देश्य के लिए बनाया गया एक और एपीआई है पर एक नजर डालें। कुछ नमूना 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/

+0

आप कनेक्शन अपने आप को बंद करने के लिए की जरूरत है या getDatabase() विधि क्या करता है कि आप के लिए है? –

+0

@AndrewSwan - SchemaCrawler आपके लिए कनेक्शन बंद नहीं करेगा। आपको इसे स्वयं बंद करना होगा। –

+0

उस स्थिति में आप अपना उदाहरण अपडेट करना चाहेंगे ताकि अंत में ब्लॉक में कनेक्शन बंद हो जाए? –

संबंधित मुद्दे

 संबंधित मुद्दे