Example usage for java.sql ResultSetMetaData getColumnClassName

List of usage examples for java.sql ResultSetMetaData getColumnClassName

Introduction

In this page you can find the example usage for java.sql ResultSetMetaData getColumnClassName.

Prototype

String getColumnClassName(int column) throws SQLException;

Source Link

Document

Returns the fully-qualified name of the Java class whose instances are manufactured if the method ResultSet.getObject is called to retrieve a value from the column.

Usage

From source file:pe.com.mmh.sisgap.utils.RowSetDynaClass.java

/**
 * <p>Factory method to create a new DynaProperty for the given index
 * into the result set metadata.</p>
 * /*from  w w  w. j  a v  a 2s  .  com*/
 * @param metadata is the result set metadata
 * @param i is the column index in the metadata
 * @return the newly created DynaProperty instance
 */
protected DynaProperty createDynaProperty(ResultSetMetaData metadata, int i) throws SQLException {

    String name = null;
    if (lowerCase) {
        name = metadata.getColumnName(i).toLowerCase();
    } else {
        name = metadata.getColumnName(i);
    }
    String className = null;
    try {
        className = metadata.getColumnClassName(i);
    } catch (SQLException e) {
        // this is a patch for HsqlDb to ignore exceptions
        // thrown by its metadata implementation
    }

    // Default to Object type if no class name could be retrieved
    // from the metadata
    Class clazz = Object.class;
    if (className != null) {
        clazz = loadClass(className);
    }
    return new DynaProperty(name, clazz);

}

From source file:org.apache.bigtop.itest.hive.TestJdbc.java

@Test
public void preparedStmtAndResultSet() throws SQLException {
    final String tableName = "bigtop_jdbc_psars_test_table";
    try (Statement stmt = conn.createStatement()) {
        stmt.execute("drop table if exists " + tableName);
        stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, "
                + "i int, lo bigint, sh smallint, st varchar(32))");
    }//from w  w  w  .j av  a 2 s.c  o  m

    // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I
    // try to put them in the query.
    try (PreparedStatement ps = conn
            .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) {
        ps.setBoolean(1, true);
        ps.setByte(2, (byte) 1);
        ps.setDouble(3, 3.141592654);
        ps.setFloat(4, 3.14f);
        ps.setInt(5, 3);
        ps.setLong(6, 10L);
        ps.setShort(7, (short) 20);
        ps.setString(8, "abc");
        ps.executeUpdate();
    }

    try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
        ps.setNull(1, Types.INTEGER);
        ps.setObject(2, "mary had a little lamb");
        ps.executeUpdate();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.clearParameters();
        ps.setNull(1, Types.INTEGER, null);
        ps.setString(2, "its fleece was white as snow");
        ps.execute();

    }

    try (Statement stmt = conn.createStatement()) {

        ResultSet rs = stmt.executeQuery("select * from " + tableName);

        ResultSetMetaData md = rs.getMetaData();

        int colCnt = md.getColumnCount();
        LOG.debug("Column count is " + colCnt);

        for (int i = 1; i <= colCnt; i++) {
            LOG.debug("Looking at column " + i);
            String strrc = md.getColumnClassName(i);
            LOG.debug("Column class name is " + strrc);

            int intrc = md.getColumnDisplaySize(i);
            LOG.debug("Column display size is " + intrc);

            strrc = md.getColumnLabel(i);
            LOG.debug("Column label is " + strrc);

            strrc = md.getColumnName(i);
            LOG.debug("Column name is " + strrc);

            intrc = md.getColumnType(i);
            LOG.debug("Column type is " + intrc);

            strrc = md.getColumnTypeName(i);
            LOG.debug("Column type name is " + strrc);

            intrc = md.getPrecision(i);
            LOG.debug("Precision is " + intrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            boolean boolrc = md.isAutoIncrement(i);
            LOG.debug("Is auto increment? " + boolrc);

            boolrc = md.isCaseSensitive(i);
            LOG.debug("Is case sensitive? " + boolrc);

            boolrc = md.isCurrency(i);
            LOG.debug("Is currency? " + boolrc);

            intrc = md.getScale(i);
            LOG.debug("Scale is " + intrc);

            intrc = md.isNullable(i);
            LOG.debug("Is nullable? " + intrc);

            boolrc = md.isReadOnly(i);
            LOG.debug("Is read only? " + boolrc);

        }

        while (rs.next()) {
            LOG.debug("bo = " + rs.getBoolean(1));
            LOG.debug("bo = " + rs.getBoolean("bo"));
            LOG.debug("ti = " + rs.getByte(2));
            LOG.debug("ti = " + rs.getByte("ti"));
            LOG.debug("db = " + rs.getDouble(3));
            LOG.debug("db = " + rs.getDouble("db"));
            LOG.debug("fl = " + rs.getFloat(4));
            LOG.debug("fl = " + rs.getFloat("fl"));
            LOG.debug("i = " + rs.getInt(5));
            LOG.debug("i = " + rs.getInt("i"));
            LOG.debug("lo = " + rs.getLong(6));
            LOG.debug("lo = " + rs.getLong("lo"));
            LOG.debug("sh = " + rs.getShort(7));
            LOG.debug("sh = " + rs.getShort("sh"));
            LOG.debug("st = " + rs.getString(8));
            LOG.debug("st = " + rs.getString("st"));
            LOG.debug("tm = " + rs.getObject(8));
            LOG.debug("tm = " + rs.getObject("st"));
            LOG.debug("tm was null " + rs.wasNull());
        }
        LOG.debug("bo is column " + rs.findColumn("bo"));

        int intrc = rs.getConcurrency();
        LOG.debug("concurrency " + intrc);

        intrc = rs.getFetchDirection();
        LOG.debug("fetch direction " + intrc);

        intrc = rs.getType();
        LOG.debug("type " + intrc);

        Statement copy = rs.getStatement();

        SQLWarning warning = rs.getWarnings();
        while (warning != null) {
            LOG.debug("Found a warning: " + warning.getMessage());
            warning = warning.getNextWarning();
        }
        rs.clearWarnings();
    }
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

/**
 *
 *///from  w  ww . j  a v  a2 s. co  m
private Integer getColumnIndex(JRField field) throws JRException {
    String fieldName = field.getName();
    Integer columnIndex = columnIndexMap.get(fieldName);
    if (columnIndex == null) {
        try {
            columnIndex = searchColumnByName(field);

            if (columnIndex == null) {
                columnIndex = searchColumnByLabel(field);
            }

            if (columnIndex == null) {
                columnIndex = searchColumnByIndex(field);
            }

            if (columnIndex == null) {
                columnIndex = searchColumnByName(fieldName);
            }

            if (columnIndex == null) {
                columnIndex = searchColumnByLabel(fieldName);
            }

            if (columnIndex == null && fieldName.startsWith(INDEXED_COLUMN_PREFIX)) {
                columnIndex = searchColumnByIndex(fieldName.substring(INDEXED_COLUMN_PREFIX_LENGTH));
            }

            if (columnIndex == null) {
                throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_UNKNOWN_COLUMN_NAME,
                        new Object[] { fieldName });
            }
        } catch (SQLException e) {
            throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_METADATA_NOT_RETRIEVED, null, e);
        }

        if (log.isDebugEnabled()) {
            try {
                ResultSetMetaData metaData = resultSet.getMetaData();
                log.debug("field " + fieldName + " has type " + metaData.getColumnType(columnIndex) + "/"
                        + metaData.getColumnTypeName(columnIndex) + ", class "
                        + metaData.getColumnClassName(columnIndex));
            } catch (SQLException e) {
                log.debug("failed to read result set metadata", e);
            }
        }

        columnIndexMap.put(fieldName, columnIndex);
    }

    return columnIndex;
}

From source file:org.apache.calcite.avatica.jdbc.JdbcMeta.java

/**
 * Convert from JDBC metadata to Avatica columns.
 *//*from  w w  w.  j a v  a  2 s  . co  m*/
protected static List<ColumnMetaData> columns(ResultSetMetaData metaData) throws SQLException {
    if (metaData == null) {
        return Collections.emptyList();
    }
    final List<ColumnMetaData> columns = new ArrayList<>();
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        final SqlType sqlType = SqlType.valueOf(metaData.getColumnType(i));
        final ColumnMetaData.Rep rep = ColumnMetaData.Rep.of(sqlType.internal);
        ColumnMetaData.AvaticaType t = ColumnMetaData.scalar(metaData.getColumnType(i),
                metaData.getColumnTypeName(i), rep);
        ColumnMetaData md = new ColumnMetaData(i - 1, metaData.isAutoIncrement(i), metaData.isCaseSensitive(i),
                metaData.isSearchable(i), metaData.isCurrency(i), metaData.isNullable(i), metaData.isSigned(i),
                metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i),
                metaData.getSchemaName(i), metaData.getPrecision(i), metaData.getScale(i),
                metaData.getTableName(i), metaData.getCatalogName(i), t, metaData.isReadOnly(i),
                metaData.isWritable(i), metaData.isDefinitelyWritable(i), metaData.getColumnClassName(i));
        columns.add(md);
    }
    return columns;
}

From source file:com.serphacker.serposcope.db.base.ExportDB.java

public boolean export(Writer writer) throws IOException {
    for (String resource : MigrationDB.DB_SCHEMA_FILES) {
        String sql = new String(ByteStreams.toByteArray(MigrationDB.class.getResourceAsStream(resource)));
        sql = sql.replaceAll("--.*\n", "\n");
        sql = sql.replaceAll("\\s+", " ");
        sql = sql.replaceAll(";\\s*", ";\n");
        writer.append(sql);//ww w .ja v  a2 s  . c  o  m
        writer.append("\n");
    }

    writer.append("\nSET FOREIGN_KEY_CHECKS=0;\n");
    try (Connection con = ds.getConnection()) {
        for (String table : TABLES) {
            writer.flush();
            try (Statement stmt = con.createStatement()) {
                LOG.info("exporting table {}", table);
                long _start = System.currentTimeMillis();

                stmt.setQueryTimeout(3600 * 24);
                ResultSet rs = stmt.executeQuery("SELECT * FROM `" + table + "`");
                ResultSetMetaData metaData = rs.getMetaData();
                int columns = metaData.getColumnCount();

                String insertStatement = "INSERT INTO `" + table + "` VALUES ";

                StringBuilder stmtBuilder = new StringBuilder(insertStatement);
                while (rs.next()) {

                    StringBuilder entryBuilder = new StringBuilder("(");
                    for (int colIndex = 1; colIndex <= columns; colIndex++) {
                        Object object = rs.getObject(colIndex);
                        String colName = metaData.getColumnName(colIndex);
                        String colClassName = metaData.getColumnClassName(colIndex);
                        String escaped = escape(object, colClassName, colName);
                        entryBuilder.append(escaped);
                        if (colIndex < columns) {
                            entryBuilder.append(',');
                        }
                    }
                    entryBuilder.append("),");

                    if (stmtBuilder.length() != insertStatement.length()
                            && stmtBuilder.length() + entryBuilder.length() > DEFAULT_MAX_ALLOWED_PACKET) {
                        stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                        writer.append(stmtBuilder).append('\n');
                        stmtBuilder = new StringBuilder(insertStatement);
                    }

                    stmtBuilder.append(entryBuilder);
                }

                if (stmtBuilder.length() != insertStatement.length()) {
                    stmtBuilder.setCharAt(stmtBuilder.length() - 1, ';');
                    writer.append(stmtBuilder).append('\n');
                }

                LOG.info("exported table {} in {}", table,
                        DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - _start));
            }
        }
        writer.append("SET FOREIGN_KEY_CHECKS=1;\n");
    } catch (Exception ex) {
        LOG.error("SQL error", ex);
        return false;
    }

    return true;
}

From source file:com.hangum.tadpole.rdb.core.editors.table.TableViewerEditPart.java

/**
 * ??  ./*from  w ww.j  a va  2 s . c  o  m*/
 * 
 * 1) ResultSetMetaData  ??  ? .
 * 
 * @param requestQuery
 * @param startResultPos
 * @param endResultPos
 */
private void runSQLSelect(String whereSQL) throws Exception {
    String requestQuery = "SELECT * FROM " + initTableNameStr; //$NON-NLS-1$
    if (!"".equals(whereSQL)) { //$NON-NLS-1$
        requestQuery += " where " + whereSQL; //$NON-NLS-1$
    }

    //  .
    //
    //
    //
    //
    //      if(DBDefine.MSSQL_DEFAULT != DBDefine.getDBDefine(userDB.getTypes())) {
    requestQuery = PartQueryUtil.makeSelect(userDB, requestQuery, 0, 500);
    //      } else {
    //         requestQuery = requestQuery + " top 500";
    //      }

    ResultSet rs = null;
    java.sql.Connection javaConn = null;

    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();

        PreparedStatement stmt = null;
        stmt = javaConn.prepareStatement(requestQuery);

        rs = stmt.executeQuery();//Query( selText );

        // table column? 
        ResultSetMetaData rsm = rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        for (int i = 0; i < rsm.getColumnCount(); i++) {
            //            if(logger.isDebugEnabled()) logger.debug(i + "[type]" + rsm.getColumnClassName(i+1) ); //$NON-NLS-1$
            tableDataTypeList.put(i, rsm.getColumnClassName(i + 1));
        }

        // rs set? ?? 
        tableDataList = new ArrayList<HashMap<Integer, Object>>();
        originalDataList = new ArrayList<HashMap<Integer, Object>>();
        HashMap<Integer, Object> tmpRs = null;

        mapColumns = SQLUtil.mataDataToMap(rs);

        while (rs.next()) {
            tmpRs = new HashMap<Integer, Object>();

            /** column modify info */
            tmpRs.put(0, TbUtils.COLUMN_MOD_TYPE.NONE.toString());

            for (int i = 1; i < columnCount + 1; i++) {
                try {
                    tmpRs.put(i, XMLUtils.xmlToString(rs.getString(i) == null ? "" : rs.getString(i)));
                } catch (Exception e) {
                    logger.error("ResutSet fetch error", e);
                    tmpRs.put(i, "");
                }
            }

            tableDataList.add(tmpRs);
            // ??  update where  .
            HashMap<Integer, Object> clondRs = (HashMap<Integer, Object>) tmpRs.clone();
            originalDataList.add(clondRs);
        }

    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            javaConn.close();
        } catch (Exception e) {
        }
    }
}

From source file:bs.global.util.ExcelFactory.java

public void generate(OutputStream outputStream) throws Exception {
    try {/*w  ww  .  j  a  v  a 2 s  . c o m*/
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

        if (formatTypes != null && formatTypes.length != resultSetMetaData.getColumnCount()) {
            throw new IllegalStateException("Number of types is not identical to number of resultset columns. "
                    + "Number of types: " + formatTypes.length + ". Number of columns: "
                    + resultSetMetaData.getColumnCount());
        }

        int currentRow = 0;
        HSSFRow row = sheet.createRow(currentRow);
        int numCols = resultSetMetaData.getColumnCount();
        boolean isAutoDecideFormatTypes;

        if (isAutoDecideFormatTypes = (formatTypes == null)) {
            formatTypes = new FormatType[numCols];
        }
        for (int i = 0; i < numCols; i++) {
            String title = resultSetMetaData.getColumnName(i + 1);
            writeCell(row, i, title, FormatType.TEXT, boldFont);
            if (isAutoDecideFormatTypes) {
                Class _class = Class.forName(resultSetMetaData.getColumnClassName(i + 1));
                formatTypes[i] = getFormatType(_class);
            }
        }
        currentRow++;
        // Write report rows
        while (resultSet.next()) {
            row = sheet.createRow(currentRow++);
            for (int i = 0; i < numCols; i++) {
                Object value = resultSet.getObject(i + 1);
                writeCell(row, i, value, formatTypes[i]);
            }
        }
        // Autosize columns
        for (int i = 0; i < numCols; i++) {
            sheet.autoSizeColumn((short) i);
        }
        workbook.write(outputStream);
    } finally {
        outputStream.close();
    }
}

From source file:com.hangum.tadpole.rdb.core.editors.objects.table.TableDirectEditorComposite.java

/**
 * ??  .//from w  w w . ja  va 2 s  . co m
 * 
 * 1) ResultSetMetaData  ??  ? .
 * 
 * @param strWhere
 * @param strOrderBy
 */
private void runSQLSelect(String strWhere, String strOrderBy) throws Exception {
    String requestQuery = "SELECT "; //$NON-NLS-1$

    if (userDB.getDBDefine() == DBDefine.ORACLE_DEFAULT) {
        requestQuery += " rowid, "; //$NON-NLS-1$
    } else if (userDB.getDBDefine() == DBDefine.POSTGRE_DEFAULT) {
        requestQuery += " ctid, "; //$NON-NLS-1$
    }
    List<TableColumnDAO> tmpTableColumns = TadpoleObjectQuery.getTableColumns(userDB, tableDao);
    for (int i = 0; i < tmpTableColumns.size(); i++) {
        TableColumnDAO tabledao = tmpTableColumns.get(i);
        requestQuery += tabledao.getName();
        if (i < (tmpTableColumns.size() - 1))
            requestQuery += ","; //$NON-NLS-1$
    }

    requestQuery += " FROM " + SQLUtil.getTableName(userDB, tableDao);

    if (!"".equals(strWhere)) //$NON-NLS-1$
        requestQuery += " where " + strWhere; //$NON-NLS-1$
    if (!"".equals(strOrderBy)) //$NON-NLS-1$
        requestQuery += " order by " + strOrderBy; //$NON-NLS-1$
    if (logger.isDebugEnabled())
        logger.debug("Last query is " + requestQuery);

    ResultSet rs = null;
    java.sql.Connection javaConn = null;

    try {
        SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
        javaConn = client.getDataSource().getConnection();

        PreparedStatement stmt = null;
        stmt = javaConn.prepareStatement(requestQuery);
        stmt.setMaxRows(GetPreferenceGeneral.getSelectLimitCount());

        rs = stmt.executeQuery();

        // table column? 
        ResultSetMetaData rsm = rs.getMetaData();
        int columnCount = rsm.getColumnCount();
        for (int i = 0; i < rsm.getColumnCount(); i++) {
            //            if(logger.isDebugEnabled()) logger.debug(i + "[type]" + rsm.getColumnClassName(i+1) ); //$NON-NLS-1$
            tableDataTypeList.put(i, rsm.getColumnClassName(i + 1));
        }

        // rs set? ?? 
        tableDataList = new ArrayList<Map<Integer, Object>>();
        originalDataList = new ArrayList<Map<Integer, Object>>();
        HashMap<Integer, Object> tmpRs = null;

        mapColumns = ResultSetUtils.getColumnName(rs);

        while (rs.next()) {
            tmpRs = new HashMap<Integer, Object>();

            /** column modify info */
            tmpRs.put(0, TbUtils.COLUMN_MOD_TYPE.NONE.toString());

            for (int i = 1; i < columnCount + 1; i++) {
                try {
                    String strValue = rs.getString(i) == null ? "" : rs.getString(i);
                    //                  System.out.println("ogiginal: "+ strValue);
                    //                  strValue = StringEscapeUtils.unescapeHtml(strValue);
                    //                  System.out.println("unescapeHtml: "+ strValue);
                    //                  strValue = StringEscapeUtils.unescapeXml(strValue);
                    //                  System.out.println("unescapeXml: "+ strValue);
                    strValue = StringEscapeUtils.escapeXml(strValue);

                    tmpRs.put(i, strValue); //$NON-NLS-1$
                } catch (Exception e) {
                    logger.error("ResutSet fetch error", e); //$NON-NLS-1$
                    tmpRs.put(i, ""); //$NON-NLS-1$
                }
            }

            tableDataList.add(tmpRs);
            // ??  update where  .
            Map<Integer, Object> clondRs = (Map<Integer, Object>) tmpRs.clone();
            originalDataList.add(clondRs);
        }

    } finally {
        try {
            rs.close();
        } catch (Exception e) {
        }
        try {
            javaConn.close();
        } catch (Exception e) {
        }
    }
}

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

/**
 * @param dbName     ???/*from ww w  . j a  v  a 2s . 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.getDefaultConnectionHolder();
        String _dbType = _connHolder.getDialect().getName();
        DatabaseMetaData _dbMetaData = _connHolder.getConnection().getMetaData();
        System.out.println(">>> Catalog: " + dbName);
        System.out.println(">>> Schema: " + dbUserName);
        System.out.println(">>> Table: " + tableName);
        _resultSet = _dbMetaData.getPrimaryKeys(dbName,
                _dbType.equalsIgnoreCase("oracle") ? dbUserName.toUpperCase() : dbUserName, tableName);
        if (_resultSet == null) {
            System.err.println("Database table \"" + tableName + "\" primaryKey resultSet is null, ignored");
            return null;
        } else {
            while (_resultSet.next()) {
                _pkFields.add(_resultSet.getString(4).toLowerCase());
            }
            if (_pkFields.isEmpty()) {
                System.err
                        .println("Database table \"" + tableName + "\" does not set the primary key, ignored");
                return null;
            } else {
                //
                System.out.println(">>> " + "COLUMN_NAME / " + "COLUMN_CLASS_NAME / " + "PRIMARY_KEY / "
                        + "AUTO_INCREMENT / " + "SIGNED / " + "PRECISION / " + "SCALE / " + "NULLABLE / "
                        + "DEFAULT / " + "REMARKS");
                //
                _statement = _connHolder.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                _resultSet = _statement.executeQuery(
                        "SELECT * FROM ".concat(_connHolder.getDialect().wrapIdentifierQuote(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(),
                                        _rsMetaData.getColumnClassName(_idx), _rsMetaData.isAutoIncrement(_idx),
                                        _rsMetaData.isSigned(_idx), _rsMetaData.getPrecision(_idx),
                                        _rsMetaData.getScale(_idx), _rsMetaData.isNullable(_idx),
                                        _column.getString("COLUMN_DEF"), _column.getString("REMARKS")));
                        System.out.println("--> " + _rsMetaData.getColumnName(_idx).toLowerCase() + "\t"
                                + _rsMetaData.getColumnClassName(_idx) + "\t"
                                + _pkFields.contains(_rsMetaData.getColumnName(_idx).toLowerCase()) + "\t"
                                + _rsMetaData.isAutoIncrement(_idx) + "\t" + _rsMetaData.isSigned(_idx) + "\t"
                                + _rsMetaData.getPrecision(_idx) + "\t" + _rsMetaData.getScale(_idx) + "\t"
                                + _rsMetaData.isNullable(_idx) + "\t" + _column.getString("COLUMN_DEF") + "\t"
                                + _column.getString("REMARKS"));
                    }
                    _column.close();
                }
            }
        }
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    } finally {
        if (_statement != null) {
            try {
                _statement.close();
            } catch (SQLException e) {
                _LOG.warn("", e);
            }
        }
        if (_resultSet != null) {
            try {
                _resultSet.close();
            } catch (SQLException e) {
                _LOG.warn("", e);
            }
        }
        if (_connHolder != null) {
            _connHolder.release();
        }
    }
    return _meta;
}

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

/**
 * @param dbName ???/*from w ww.  ja v  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;
}