Java 数据库元数据

获取表元数据:

String[] types =   
            { "TABLE" };   
            ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);   
            while (rs.next())   
            {   
                String tableName = rs.getString("TABLE_NAME");   
                // table type. Typical types are "TABLE", "VIEW", "SYSTEM   
                // TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS",   
                // "SYNONYM".   
                String tableType = rs.getString("TABLE_TYPE");   
                // explanatory comment on the table   
                String remarks = rs.getString("REMARKS");   
                System.out.println(tableName + "-" + tableType + "-" + remarks);   
            }   

 

获取表各列元数据方式如下:

public TableMeta getTableMeta(String tableName) throws Exception{
        DatabaseMetaData dmd = con.getMetaData();
        ResultSet rs4PKey = dmd.getPrimaryKeys(catalog, scheme, tableName);
        ResultSet rs4FKey = dmd.getExportedKeys(catalog, scheme, tableName);
        ResultSet rs = dmd.getColumns(catalog, scheme, tableName, "%");
        TableMeta tm = new TableMeta();
        tm.setType("TABLE");
        tm.setShem(scheme);
        tm.setName(tableName);
        tm.setCols(handleRs(rs));
        tm.setKey(handleKeys(rs4PKey));
        tm.setfKey(handleFKeys(rs4FKey));
        return tm;
    }
    private Set<ColumnMeta> handleRs(ResultSet rs) throws Exception{
        Set<ColumnMeta> columns = new HashSet<ColumnMeta>();
        while (rs.next()) {
            ColumnMeta c = new ColumnMeta();
            c.setName(rs.getString("COLUMN_NAME"));
            c.setJdbcType(Integer.parseInt(rs.getString("DATA_TYPE")));
            c.setColumnSize(Integer.parseInt(rs.getString("COLUMN_SIZE")));
            c.setIsNull(rs.getString("IS_NULLABLE"));
            c.setRemark(rs.getString("REMARKS"));
            columns.add(c);
        }
        return columns;
    }
    
    private Set<PrimaryKeyMeta> handleKeys(ResultSet rs) throws Exception{
        Set<PrimaryKeyMeta> columns = new HashSet<PrimaryKeyMeta>();
        while (rs.next()) {
            PrimaryKeyMeta c = new PrimaryKeyMeta();
            c.setColumnName(rs.getString("COLUMN_NAME"));
            columns.add(c);
        }
        return columns;
    }
    
    private Set<ForeignKeyMeta> handleFKeys(ResultSet rs) throws Exception{
        Set<ForeignKeyMeta> columns = new HashSet<ForeignKeyMeta>();
        while (rs.next()) {
            ForeignKeyMeta c = new ForeignKeyMeta();
            c.setFkColumnName(rs.getString("FKCOLUMN_NAME"));
            c.setPkTableName(rs.getString("PKTABLE_NAME"));
            c.setPkColumnName(rs.getString("PKCOLUMN_NAME"));
            columns.add(c);
        }
        return columns;
    }

 参考:http://my.oschina.net/lison/blog/5434

你可能感兴趣的:(java)