SchemaCrawler的使用,提取数据库结构

jopen 11年前

看到了一篇关于操作jdbc MetaData的文章,讲的是一个开源项目,就是SchemaCrawler,看了一下,觉得作者经验挺丰富的,估计源码肯定很不错.去http://sourceforge.net/projects/schemacrawler/把他下了来.研究一番.

SchemaCrawler-3.7-distrib中有一些例子.这个开源工具功能还是很强大的,先实验一下简单的功能吧.呵呵.

1.打开eclipse,新建一个工程schema.

2.在schema的工程上添加外部jar文件,把schemacrawler-3.7.jar添加到里面.

3.添加数据库jdbc包,我使用mysql,使用mysql的jdbc包.

4.数据库新建一个数据库schema.并添加下面的表.

CREATE TABLE customer
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date date)

5.建立schema包,并建立Test类.代码如下.

package schema;    import java.util.Properties;  import javax.sql.DataSource;  import schemacrawler.crawl.SchemaCrawler;  import schemacrawler.crawl.SchemaCrawlerOptions;  import schemacrawler.crawl.SchemaInfoLevel;  import schemacrawler.schema.Column;  import schemacrawler.schema.Schema;  import schemacrawler.schema.Table;  import dbconnector.datasource.PropertiesDataSource;  import dbconnector.datasource.PropertiesDataSourceException;    public class Test {   /**    *    * @param args    * @throws Exception    */   public static void main(String args[]) throws Exception{       final DataSource dataSource = makeDataSource();       final Schema schema = SchemaCrawler.getSchema(dataSource,                                                     SchemaInfoLevel.BASIC,                                                     new SchemaCrawlerOptions());       final Table[] tables = schema.getTables();       for (int i = 0; i < tables.length; i++)       {         final Table table = tables[i];         System.out.println(table);         final Column[] columns = table.getColumns();         for (int j = 0; j < columns.length; j++)         {           final Column column = columns[j];           System.out.print("-- " + column);           System.out.println("  Type:"+columns[j].getType());         }       }   }   /**    * 取得DataSource    * @return    * @throws PropertiesDataSourceException    */   private static DataSource makeDataSource()     throws PropertiesDataSourceException {    final String datasourceName = "schemacrawler";      final Properties connectionProperties = new Properties();    connectionProperties.setProperty(datasourceName + ".driver",      "com.mysql.jdbc.Driver");    connectionProperties.setProperty(datasourceName + ".url",      "jdbc:mysql://localhost:3306/schema");    connectionProperties.setProperty(datasourceName + ".user", "root");    connectionProperties.setProperty(datasourceName + ".password", "root");      return new PropertiesDataSource(connectionProperties, datasourceName);   }  }

 

测试运行,如果数据库运行正确.则可以运行成功!