Example usage for java.sql DatabaseMetaData getColumns

List of usage examples for java.sql DatabaseMetaData getColumns

Introduction

In this page you can find the example usage for java.sql DatabaseMetaData getColumns.

Prototype

ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern)
        throws SQLException;

Source Link

Document

Retrieves a description of table columns available in the specified catalog.

Usage

From source file:org.alfresco.util.schemacomp.ExportDb.java

private void extractSchema(DatabaseMetaData dbmd, String schemaName, String prefixFilter)
        throws SQLException, IllegalArgumentException, IllegalAccessException {
    if (log.isDebugEnabled()) {
        log.debug("Retrieving tables: schemaName=[" + schemaName + "], prefixFilter=[" + prefixFilter + "]");
    }/* ww w .ja  v a 2s .  co  m*/

    final ResultSet tables = dbmd.getTables(null, schemaName, prefixFilter,
            new String[] { "TABLE", "VIEW", "SEQUENCE" });

    while (tables.next()) {
        final String tableName = tables.getString("TABLE_NAME");

        if (log.isDebugEnabled()) {
            log.debug("Examining table tableName=[" + tableName + "]");
        }

        // Oracle hack: ignore tables in the recycle bin
        // ALF-14129 fix, check whether schema already contains object with provided name
        if (tableName.startsWith("BIN$") || schema.containsByName(tableName)) {
            continue;
        }

        if (tables.getString("TABLE_TYPE").equals("SEQUENCE")) {
            Sequence sequence = new Sequence(tableName);
            schema.add(sequence);
            continue;
        }

        Table table = new Table(tableName);
        schema.add(table);

        // Table columns
        final ResultSet columns = dbmd.getColumns(null, tables.getString("TABLE_SCHEM"), tableName, "%");
        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            Column column = new Column(columnName);

            String dbType = columns.getString("TYPE_NAME");
            int colSize = columns.getInt("COLUMN_SIZE");
            int scale = columns.getInt("DECIMAL_DIGITS");
            int jdbcType = columns.getInt("DATA_TYPE");
            String type = generateType(dbType, colSize, scale, jdbcType);
            column.setType(type);

            String nullableString = columns.getString("IS_NULLABLE");
            column.setNullable(parseBoolean(nullableString));

            column.setOrder(columns.getInt("ORDINAL_POSITION"));

            try {
                String autoIncString = columns.getString("IS_AUTOINCREMENT");
                column.setAutoIncrement(parseBoolean(autoIncString));
            } catch (SQLException jtdsDoesNOtHAveIsUatoincrement) {
                column.setAutoIncrement((dbType.endsWith("identity")));
            }

            column.setParent(table);
            table.getColumns().add(column);
        }
        columns.close();

        // Primary key
        final ResultSet primarykeycols = dbmd.getPrimaryKeys(null, tables.getString("TABLE_SCHEM"), tableName);

        PrimaryKey pk = null;

        while (primarykeycols.next()) {
            if (pk == null) {
                String pkName = primarykeycols.getString("PK_NAME");
                pk = new PrimaryKey(pkName);
            }
            String columnName = primarykeycols.getString("COLUMN_NAME");
            pk.getColumnNames().add(columnName);

            int columnOrder = primarykeycols.getInt("KEY_SEQ");
            pk.getColumnOrders().add(columnOrder);
        }
        primarykeycols.close();

        // If this table has a primary key, add it. 
        if (pk != null) {
            pk.setParent(table);
            table.setPrimaryKey(pk);
        }

        // Indexes
        final ResultSet indexes = dbmd.getIndexInfo(null, tables.getString("TABLE_SCHEM"), tableName, false,
                true);
        String lastIndexName = "";

        Index index = null;

        while (indexes.next()) {
            final String indexName = indexes.getString("INDEX_NAME");
            if (indexName == null) {
                // Oracle seems to have some dummy index entries
                continue;
            }
            // Skip the index corresponding to the PK if it is mentioned
            else if (indexName.equals(table.getPrimaryKey().getName())) {
                continue;
            }

            if (!indexName.equals(lastIndexName)) {
                index = new Index(indexName);
                index.setUnique(!indexes.getBoolean("NON_UNIQUE"));
                index.setParent(table);
                table.getIndexes().add(index);
                lastIndexName = indexName;
            }
            if (index != null) {
                String columnName = indexes.getString("COLUMN_NAME");
                index.getColumnNames().add(columnName);
            }
        }
        indexes.close();

        final ResultSet foreignkeys = dbmd.getImportedKeys(null, tables.getString("TABLE_SCHEM"), tableName);
        String lastKeyName = "";

        ForeignKey fk = null;

        while (foreignkeys.next()) {
            final String keyName = foreignkeys.getString("FK_NAME");
            if (!keyName.equals(lastKeyName)) {
                fk = new ForeignKey(keyName);
                fk.setParent(table);
                table.getForeignKeys().add(fk);
                lastKeyName = keyName;
            }
            if (fk != null) {
                fk.setLocalColumn(foreignkeys.getString("FKCOLUMN_NAME"));
                fk.setTargetTable(foreignkeys.getString("PKTABLE_NAME"));
                fk.setTargetColumn(foreignkeys.getString("PKCOLUMN_NAME"));
            }
        }
        foreignkeys.close();
    }
    tables.close();
}

From source file:org.nuclos.server.masterdata.ejb3.MetaDataFacadeBean.java

/**
 * @return Script (with results if selected)
 *//*from  ww w  . j  a  v a  2s.  c  o  m*/
@Override
@RolesAllowed("Login")
public MasterDataMetaVO transferTable(String url, String user, String password, String schema, String table,
        String sEntity) {

    MasterDataMetaVO metaNew = null;

    Connection connect = null;
    try {
        DependantMasterDataMap dependMap = new DependantMasterDataMapImpl();
        List<String> lstFields = new ArrayList<String>();
        connect = DriverManager.getConnection(url, user, password);
        DatabaseMetaData dbmeta = connect.getMetaData();
        ResultSet rsCols = dbmeta.getColumns(null, schema.toUpperCase(), table, "%");
        while (rsCols.next()) {
            String colName = rsCols.getString("COLUMN_NAME");
            int colsize = rsCols.getInt("COLUMN_SIZE");
            int postsize = rsCols.getInt("DECIMAL_DIGITS");
            int columsType = rsCols.getInt("DATA_TYPE");
            String sJavaType = getBestJavaType(columsType);
            if (postsize > 0)
                sJavaType = "java.lang.Double";

            MasterDataMetaVO metaFieldVO = masterDataFacade
                    .getMetaData(NuclosEntity.ENTITYFIELD.getEntityName());
            MasterDataVO mdFieldVO = new MasterDataVO(metaFieldVO, false);

            mdFieldVO.setField("foreignentityfield", null);
            mdFieldVO.setField("unique", Boolean.FALSE);
            mdFieldVO.setField("logbook", Boolean.FALSE);
            mdFieldVO.setField("entity", NuclosEntity.ENTITYFIELD.getEntityName());
            mdFieldVO.setField("formatinput", null);
            mdFieldVO.setField("entityId", null);
            mdFieldVO.setField("datascale", colsize);
            mdFieldVO.setField("label", org.apache.commons.lang.StringUtils.capitalize(colName.toLowerCase()));
            mdFieldVO.setField("nullable", Boolean.TRUE);
            mdFieldVO.setField("dataprecision", postsize);
            mdFieldVO.setField("dbfield", colName.toLowerCase());
            mdFieldVO.setField("description",
                    org.apache.commons.lang.StringUtils.capitalize(colName.toLowerCase()));
            mdFieldVO.setField("name", colName.toLowerCase());
            mdFieldVO.setField("entityfieldDefault", null);
            mdFieldVO.setField("foreignentity", null);
            mdFieldVO.setField("formatoutput", null);
            mdFieldVO.setField("datatype", sJavaType);
            mdFieldVO.setField("searchable", Boolean.FALSE);
            mdFieldVO.setField("foreignentity", null);
            mdFieldVO.setField("foreignentityfield", null);

            final String entity = NuclosEntity.ENTITYFIELD.getEntityName();
            dependMap.addData(entity, DalSupportForMD.getEntityObjectVO(entity, mdFieldVO));
            lstFields.add(colName);
        }

        rsCols.close();

        metaNew = masterDataFacade.getMetaData(sEntity);

        String sqlSelect = "select * from " + schema + "." + table;
        Statement stmt = connect.createStatement();
        ResultSet rsSelect = stmt.executeQuery(sqlSelect);
        while (rsSelect.next()) {
            List<Object> lstValues = new ArrayList<Object>();
            for (String sColname : lstFields) {
                lstValues.add(rsSelect.getObject(sColname));
            }

            StringBuffer sb = new StringBuffer();
            sb.append("insert into " + metaNew.getDBEntity());
            sb.append(" values(?");
            for (int i = 0; i < lstValues.size(); i++) {
                sb.append(",?");
            }
            sb.append(",?,?,?,?,?)");

            int col = 1;
            PreparedStatement pst = dataSource.getConnection().prepareStatement(sb.toString());
            pst.setInt(col++, dataBaseHelper.getNextIdAsInteger(SpringDataBaseHelper.DEFAULT_SEQUENCE));
            for (Object object : lstValues) {
                pst.setObject(col++, object);
            }
            pst.setDate(col++, new java.sql.Date(System.currentTimeMillis()));
            pst.setString(col++, "Wizard");
            pst.setDate(col++, new java.sql.Date(System.currentTimeMillis()));
            pst.setString(col++, "Wizard");
            pst.setInt(col++, 1);

            pst.executeUpdate();
            pst.close();

        }
        rsSelect.close();
        stmt.close();

    } catch (SQLException e) {
        LOG.info("transferTable: " + e, e);
    } finally {
        if (connect != null)
            try {
                connect.close();
            } catch (SQLException e) {
                // do noting here
                LOG.info("transferTable: " + e);
            }
    }
    return metaNew;
}

From source file:com.glaf.core.util.DBUtils.java

public static List<ColumnDefinition> getColumnDefinitions(Connection conn, String tableName) {
    List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>();
    ResultSet rs = null;/*from w w  w .j a  va 2 s  .co  m*/
    try {
        List<String> primaryKeys = getPrimaryKeys(conn, tableName);
        String dbType = DBConnectionFactory.getDatabaseType(conn);
        DatabaseMetaData metaData = conn.getMetaData();
        if ("h2".equals(dbType)) {
            tableName = tableName.toUpperCase();
        } else if ("oracle".equals(dbType)) {
            tableName = tableName.toUpperCase();
        } else if ("db2".equals(dbType)) {
            tableName = tableName.toUpperCase();
        } else if ("mysql".equals(dbType)) {
            tableName = tableName.toLowerCase();
        } else if ("postgresql".equals(dbType)) {
            tableName = tableName.toLowerCase();
        }
        rs = metaData.getColumns(null, null, tableName, null);
        while (rs.next()) {
            String columnName = rs.getString("COLUMN_NAME");
            String typeName = rs.getString("TYPE_NAME");
            int dataType = rs.getInt("DATA_TYPE");
            int nullable = rs.getInt("NULLABLE");
            int length = rs.getInt("COLUMN_SIZE");
            int ordinal = rs.getInt("ORDINAL_POSITION");
            ColumnDefinition column = new ColumnDefinition();
            column.setColumnName(columnName.toLowerCase());
            column.setTitle(column.getName());
            column.setEnglishTitle(column.getName());
            column.setJavaType(FieldType.getJavaType(dataType));
            column.setName(StringTools.camelStyle(column.getColumnName().toLowerCase()));
            if (nullable == 1) {
                column.setNullable(true);
            } else {
                column.setNullable(false);
            }
            column.setLength(length);
            column.setOrdinal(ordinal);

            if ("String".equals(column.getJavaType())) {
                if (column.getLength() > 8000) {
                    column.setJavaType("Clob");
                }
            }

            if ("Double".equals(column.getJavaType())) {
                if (column.getLength() == 19) {
                    column.setJavaType("Long");
                }
            }

            if (StringUtils.equalsIgnoreCase(typeName, "bool")
                    || StringUtils.equalsIgnoreCase(typeName, "boolean")
                    || StringUtils.equalsIgnoreCase(typeName, "bit")
                    || StringUtils.equalsIgnoreCase(typeName, "tinyint")
                    || StringUtils.equalsIgnoreCase(typeName, "smallint")) {
                column.setJavaType("Boolean");
            }

            if (primaryKeys.contains(columnName.toLowerCase())) {
                column.setPrimaryKey(true);
            }

            if (!columns.contains(column)) {
                logger.debug("column name:" + column.getColumnName());
                columns.add(column);
            }
        }

        return columns;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
    }
}

From source file:com.glaf.core.util.DBUtils.java

public static List<ColumnDefinition> getColumnDefinitions(String tableName) {
    List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>();
    Connection conn = null;//from ww w.j av  a  2  s .  c  om
    ResultSet rs = null;
    try {
        List<String> primaryKeys = getPrimaryKeys(tableName);

        conn = DBConnectionFactory.getConnection();
        String dbType = DBConnectionFactory.getDatabaseType(conn);

        DatabaseMetaData metaData = conn.getMetaData();
        if ("h2".equals(dbType)) {
            tableName = tableName.toUpperCase();
        } else if ("oracle".equals(dbType)) {
            tableName = tableName.toUpperCase();
        } else if ("db2".equals(dbType)) {
            tableName = tableName.toUpperCase();
        } else if ("mysql".equals(dbType)) {
            tableName = tableName.toLowerCase();
        } else if ("postgresql".equals(dbType)) {
            tableName = tableName.toLowerCase();
        }
        rs = metaData.getColumns(null, null, tableName, null);
        while (rs.next()) {
            String name = rs.getString("COLUMN_NAME");
            String typeName = rs.getString("TYPE_NAME");
            int dataType = rs.getInt("DATA_TYPE");
            int nullable = rs.getInt("NULLABLE");
            int length = rs.getInt("COLUMN_SIZE");
            int ordinal = rs.getInt("ORDINAL_POSITION");

            ColumnDefinition column = new ColumnDefinition();
            column.setColumnName(name);
            column.setJavaType(FieldType.getJavaType(dataType));
            if (nullable == 1) {
                column.setNullable(true);
            } else {
                column.setNullable(false);
            }
            column.setLength(length);
            column.setOrdinal(ordinal);
            column.setName(StringTools.camelStyle(column.getColumnName().toLowerCase()));

            logger.debug(
                    name + " typeName:" + typeName + "[" + dataType + "] " + FieldType.getJavaType(dataType));

            if ("String".equals(column.getJavaType())) {
                if (column.getLength() > 8000) {
                    column.setJavaType("Clob");
                }
            }

            if ("Double".equals(column.getJavaType())) {
                if (column.getLength() == 19) {
                    column.setJavaType("Long");
                }
            }

            if (StringUtils.equalsIgnoreCase(typeName, "bool")
                    || StringUtils.equalsIgnoreCase(typeName, "boolean")
                    || StringUtils.equalsIgnoreCase(typeName, "bit")
                    || StringUtils.equalsIgnoreCase(typeName, "tinyint")
                    || StringUtils.equalsIgnoreCase(typeName, "smallint")) {
                column.setJavaType("Boolean");
            }

            if (primaryKeys.contains(name) || primaryKeys.contains(name.toUpperCase())
                    || primaryKeys.contains(name.toLowerCase())) {
                column.setPrimaryKey(true);
            }

            if (!columns.contains(column)) {
                columns.add(column);
            }
        }

        return columns;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(conn);
    }
}

From source file:com.kylinolap.rest.service.QueryService.java

protected List<TableMeta> getMetadata(CubeManager cubeMgr, String project, boolean cubedOnly)
        throws SQLException {

    Connection conn = null;/*from w ww .java  2 s  . c om*/
    ResultSet columnMeta = null;
    List<TableMeta> tableMetas = null;

    try {
        DataSource dataSource = getOLAPDataSource(project);
        conn = dataSource.getConnection();
        DatabaseMetaData metaData = conn.getMetaData();

        logger.debug("getting table metas");
        ResultSet JDBCTableMeta = metaData.getTables(null, null, null, null);

        tableMetas = new LinkedList<TableMeta>();
        Map<String, TableMeta> tableMap = new HashMap<String, TableMeta>();
        while (JDBCTableMeta.next()) {
            String catalogName = JDBCTableMeta.getString(1);
            String schemaName = JDBCTableMeta.getString(2);

            // Not every JDBC data provider offers full 10 columns, for
            // example,
            // PostgreSQL has only 5
            TableMeta tblMeta = new TableMeta(catalogName == null ? Constant.FakeCatalogName : catalogName,
                    schemaName == null ? Constant.FakeSchemaName : schemaName, JDBCTableMeta.getString(3),
                    JDBCTableMeta.getString(4), JDBCTableMeta.getString(5), null, null, null, null, null);

            if (!cubedOnly || getProjectManager().isExposedTable(project, tblMeta.getTABLE_NAME())) {
                tableMetas.add(tblMeta);
                tableMap.put(tblMeta.getTABLE_SCHEM() + "#" + tblMeta.getTABLE_NAME(), tblMeta);
            }
        }

        logger.debug("getting column metas");
        columnMeta = metaData.getColumns(null, null, null, null);

        while (columnMeta.next()) {
            String catalogName = columnMeta.getString(1);
            String schemaName = columnMeta.getString(2);

            // kylin(optiq) is not strictly following JDBC specification
            ColumnMeta colmnMeta = new ColumnMeta(catalogName == null ? Constant.FakeCatalogName : catalogName,
                    schemaName == null ? Constant.FakeSchemaName : schemaName, columnMeta.getString(3),
                    columnMeta.getString(4), columnMeta.getInt(5), columnMeta.getString(6),
                    columnMeta.getInt(7), getInt(columnMeta.getString(8)), columnMeta.getInt(9),
                    columnMeta.getInt(10), columnMeta.getInt(11), columnMeta.getString(12),
                    columnMeta.getString(13), getInt(columnMeta.getString(14)),
                    getInt(columnMeta.getString(15)), columnMeta.getInt(16), columnMeta.getInt(17),
                    columnMeta.getString(18), columnMeta.getString(19), columnMeta.getString(20),
                    columnMeta.getString(21), getShort(columnMeta.getString(22)), columnMeta.getString(23));

            if (!cubedOnly || getProjectManager().isExposedColumn(project, colmnMeta.getTABLE_NAME(),
                    colmnMeta.getCOLUMN_NAME())) {
                tableMap.get(colmnMeta.getTABLE_SCHEM() + "#" + colmnMeta.getTABLE_NAME()).addColumn(colmnMeta);
            }
        }
        logger.debug("done column metas");
    } finally {
        close(columnMeta, null, conn);
    }

    return tableMetas;
}

From source file:mondrian.rolap.RolapStar.java

private boolean containsColumn(String tableName, String columnName) {
    Connection jdbcConnection;/*from  w w  w .  j a va 2  s .  c  o m*/
    try {
        jdbcConnection = dataSource.getConnection();
    } catch (SQLException e1) {
        throw Util.newInternal(e1, "Error while creating connection from data source");
    }
    try {
        final DatabaseMetaData metaData = jdbcConnection.getMetaData();
        final ResultSet columns = metaData.getColumns(null, null, tableName, columnName);
        return columns.next();
    } catch (SQLException e) {
        throw Util.newInternal(
                "Error while retrieving metadata for table '" + tableName + "', column '" + columnName + "'");
    } finally {
        try {
            jdbcConnection.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:com.feedzai.commons.sql.abstraction.engine.AbstractDatabaseEngine.java

/**
 * Gets the table metadata./*www.j  av a2s . co  m*/
 *
 * @return A representation of the table columns and types.
 * @throws DatabaseEngineException If something occurs getting the metadata.
 */
@Override
public synchronized Map<String, DbColumnType> getMetadata(final String name) throws DatabaseEngineException {
    final Map<String, DbColumnType> metaMap = new LinkedHashMap<>();

    ResultSet rsColumns = null;
    try {
        getConnection();

        final DatabaseMetaData meta = conn.getMetaData();
        rsColumns = meta.getColumns(null, getSchema(), name, null);
        while (rsColumns.next()) {
            metaMap.put(rsColumns.getString("COLUMN_NAME"), toPdbType(rsColumns.getInt("DATA_TYPE")));
        }

        return metaMap;
    } catch (Exception e) {
        throw new DatabaseEngineException("Could not get metadata", e);
    } finally {
        try {
            if (rsColumns != null) {
                rsColumns.close();
            }
        } catch (Exception a) {
            logger.trace("Error closing result set.", a);
        }
    }
}

From source file:org.talend.core.model.metadata.DBConnectionFillerImplTest.java

/**
 * /*w w  w  .  jav a  2s .  c  om*/
 * test fill columns for method "fillColumns(ColumnSet colSet, DatabaseMetaData dbJDBCMetadata, List<String>
 * columnFilter, String columnPattern)"
 * 
 * @throws SQLException
 */
@Test
public void testFillColumns_1() throws SQLException {

    ColumnSet columnSet = orgomg.cwm.resource.relational.RelationalFactory.eINSTANCE.createColumnSet();
    columnSet.setName("table1");//$NON-NLS-1$
    DatabaseMetaData dbJDBCMetadata = mock(DatabaseMetaData.class);
    List<String> columnFilter = new ArrayList<String>();
    Schema schema = mock(Schema.class);
    when(schema.getName()).thenReturn("talend");//$NON-NLS-1$
    PowerMockito.mockStatic(CatalogHelper.class);
    when(CatalogHelper.getParentCatalog(columnSet)).thenReturn(null);
    PowerMockito.mockStatic(SchemaHelper.class);
    when(SchemaHelper.getParentSchema(columnSet)).thenReturn(schema);
    stub(method(MetadataConnectionUtils.class, "isSybase", DatabaseMetaData.class)).toReturn(false);//$NON-NLS-1$
    stub(method(MetadataConnectionUtils.class, "isMssql", DatabaseMetaData.class)).toReturn(false);//$NON-NLS-1$
    stub(method(MetadataConnectionUtils.class, "isOracle", DatabaseMetaData.class)).toReturn(true);//$NON-NLS-1$
    ResultSet rs = mock(ResultSet.class);

    when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
    when(rs.getString(GetColumn.COLUMN_NAME.name())).thenReturn("column1").thenReturn("column2");//$NON-NLS-1$ //$NON-NLS-2$
    when(rs.getString(GetColumn.TYPE_NAME.name())).thenReturn("VARCHAR");//$NON-NLS-1$
    when(rs.getInt(GetColumn.NULLABLE.name())).thenReturn(0);
    when(rs.getInt(GetColumn.DATA_TYPE.name())).thenReturn(1);

    when(rs.getString(GetColumn.REMARKS.name())).thenReturn("");//$NON-NLS-1$
    when(rs.getString(GetColumn.IS_NULLABLE.name())).thenReturn("YES");//$NON-NLS-1$
    when(dbJDBCMetadata.getColumns(anyString(), anyString(), anyString(), anyString())).thenReturn(rs);

    dbConnection.setDbmsId(null);
    PowerMockito.mockStatic(ConnectionHelper.class);
    when(ConnectionHelper.getConnection(columnSet)).thenReturn(dbConnection);

    stub(method(MetadataToolHelper.class, "validateValueForDBType", String.class)).toReturn("VARCHAR");//$NON-NLS-1$ //$NON-NLS-2$
    PowerMockito.mockStatic(ColumnSetHelper.class);
    stub(method(ColumnSetHelper.class, "addColumns")).toReturn(true);//$NON-NLS-1$

    List<TdColumn> fillColumns = dBConnectionFillerImpl.fillColumns(columnSet, dbJDBCMetadata, columnFilter,
            null);
    assertNotNull(fillColumns);
    assertTrue(fillColumns.size() == 2);

}

From source file:net.ymate.platform.persistence.jdbc.scaffold.JdbcScaffold.java

/**
 * @param dbName ???/*  w w w  .  jav  a  2 s .  c  o  m*/
 * @param dbUserName ??
 * @param tableName ??
 * @return ?????
 */
private TableMeta getTableMeta(String dbName, String dbUserName, String tableName) {
    IConnectionHolder _connHolder = null;
    Statement _statement = null;
    ResultSet _resultSet = null;
    Map<String, ColumnInfo> _tableFields = new LinkedHashMap<String, ColumnInfo>();
    List<String> _pkFields = new LinkedList<String>();
    TableMeta _meta = new TableMeta(_pkFields, _tableFields);
    try {
        _connHolder = JDBC.getConnectionHolder();
        String _dbType = JDBC_SCAFFOLD_CONF.getProperty("ymp.scaffold.jbdc.db_type", "unknow");
        DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData();
        _resultSet = _dbMetaData.getPrimaryKeys(dbName,
                _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName);
        if (_resultSet == null) {
            _meta = null;
            System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored");
        } else {
            while (_resultSet.next()) {
                _pkFields.add(_resultSet.getString(4).toLowerCase());
            }
            if (_pkFields.isEmpty()) {
                _meta = null;
                System.err
                        .println("Database table \"" + tableName + "\" does not set the primary key, ignored");
            } else {
                _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                _resultSet = _statement
                        .executeQuery("select * from " + _connHolder.getDialect().wapperQuotedIdent(tableName));
                ResultSetMetaData _rsMetaData = _resultSet.getMetaData();
                //
                for (int _idx = 1; _idx <= _rsMetaData.getColumnCount(); _idx++) {
                    // ??
                    ResultSet _column = _dbMetaData.getColumns(dbName,
                            _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName,
                            tableName, _rsMetaData.getColumnName(_idx));
                    if (_column.next()) {
                        // ????
                        _tableFields.put(_rsMetaData.getColumnName(_idx).toLowerCase(),
                                new ColumnInfo(_rsMetaData.getColumnName(_idx).toLowerCase(),
                                        compressType(_rsMetaData.getColumnClassName(_idx)),
                                        _rsMetaData.isAutoIncrement(_idx), _rsMetaData.isNullable(_idx),
                                        _column.getString("COLUMN_DEF")));
                    }
                }
                //
                System.err.println("TABLE_NAME: " + tableName + " ---------------->>");
                System.err.println("COLUMN_NAME\tPK\tCOLUMN_TYPE\tIS_AUTOINCREMENT\tIS_NULLABLE\tCOLUMN_DEF");
                for (ColumnInfo _cInfo : _tableFields.values()) {
                    System.err
                            .println(_cInfo.getColumnName() + "\t" + _pkFields.contains(_cInfo.getColumnName())
                                    + "\t" + _cInfo.getColumnType() + "\t" + _cInfo.isAutoIncrement() + "\t"
                                    + _cInfo.getNullable() + "\t" + _cInfo.getDefaultValue());
                }
            }
        }
    } catch (Throwable e) {
        if (e instanceof Error) {
            throw (Error) e;
        }
        throw new Error(RuntimeUtils.unwrapThrow(e));
    } finally {
        _connHolder.release();
        _statement = null;
        _resultSet = null;
    }
    return _meta;
}

From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java

@Test
public void testShow() throws Exception {
    Connection conn = getConnection("octopus", "bitnine");

    System.out.println("* Transaction isolation level");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SHOW TRANSACTION ISOLATION LEVEL");
    while (rs.next())
        System.out.println("  " + rs.getString("transaction_isolation"));
    rs.close();/*from  w  w w.ja v  a  2 s.  c om*/

    System.out.println("* DataSources");
    DatabaseMetaData metaData = conn.getMetaData();
    rs = metaData.getCatalogs();
    while (rs.next()) {
        System.out.println("  " + rs.getString("TABLE_CAT") + ", " + rs.getString("REMARKS"));
    }
    rs.close();

    System.out.println("* Schemas");
    rs = metaData.getSchemas(dataMemDb.name, "%DEFAULT");
    while (rs.next()) {
        System.out.println("  " + rs.getString("TABLE_SCHEM") + ", " + rs.getString("TABLE_CATALOG") + ", "
                + rs.getString("REMARKS") + ", " + rs.getString("TABLE_CAT_REMARKS"));
    }
    rs.close();

    System.out.println("* Tables");
    rs = metaData.getTables(dataMemDb.name, "%DEFAULT", "employee", null);
    while (rs.next()) {
        System.out.println("  " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", "
                + rs.getString("TABLE_NAME") + ", " + rs.getString("REMARKS") + ", "
                + rs.getString("TABLE_CAT_REMARKS") + ", " + rs.getString("TABLE_SCHEM_REMARKS"));
    }
    rs.close();

    System.out.println("* Columns");
    rs = metaData.getColumns(dataMemDb.name, "%DEFAULT", "employee", "%");
    while (rs.next()) {
        System.out.println("  " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", "
                + rs.getString("TABLE_NAME") + ", " + rs.getString("COLUMN_NAME") + ", "
                + rs.getString("REMARKS") + ", " + rs.getString("TABLE_CAT_REMARKS") + ", "
                + rs.getString("TABLE_SCHEM_REMARKS") + ", " + rs.getString("TABLE_NAME_REMARKS"));
    }
    rs.close();

    System.out.println("* Users");

    rs = stmt.executeQuery("SHOW ALL USERS");
    while (rs.next()) {
        System.out.println("  " + rs.getString("USER_NAME") + ", " + rs.getString("REMARKS"));
    }
    rs.close();

    stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'");
    stmt.execute("GRANT ALL ON \"" + dataMemDb.name + "\".\"__DEFAULT\" TO \"jsyang\"");
    rs = stmt.executeQuery("SHOW OBJECT PRIVILEGES FOR \"jsyang\"");
    while (rs.next()) {
        System.out.println("  " + rs.getString("TABLE_CAT") + ", " + rs.getString("TABLE_SCHEM") + ", "
                + rs.getString("PRIVILEGE"));
    }
    rs.close();
    stmt.execute("DROP USER \"jsyang\"");

    stmt.close();

    conn.close();
}