Example usage for java.sql ResultSetMetaData getPrecision

List of usage examples for java.sql ResultSetMetaData getPrecision

Introduction

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

Prototype

int getPrecision(int column) throws SQLException;

Source Link

Document

Get the designated column's specified column size.

Usage

From source file:org.openiot.gsn.storage.StorageManager.java

public DataField[] tableToStructureByString(String tableName, Connection connection) throws SQLException {
    StringBuilder sb = new StringBuilder("select * from ").append(tableName).append(" where 1=0 ");
    ResultSet rs = null;/* w  ww . jav  a 2s  . co m*/
    DataField[] toReturn = null;
    try {
        rs = executeQueryWithResultSet(sb, connection);
        ResultSetMetaData structure = rs.getMetaData();
        ArrayList<DataField> toReturnArr = new ArrayList<DataField>();
        for (int i = 1; i <= structure.getColumnCount(); i++) {
            String colName = structure.getColumnLabel(i);
            if (colName.equalsIgnoreCase("pk"))
                continue;
            if (colName.equalsIgnoreCase("timed"))
                continue;
            int colType = structure.getColumnType(i);
            String colTypeName = structure.getColumnTypeName(i);
            int precision = structure.getPrecision(i);
            byte colTypeInGSN = convertLocalTypeToGSN(colType);
            if ((colTypeInGSN == DataTypes.VARCHAR) || (colTypeInGSN == DataTypes.CHAR))
                toReturnArr.add(new DataField(colName, colTypeName, precision, colName));
            else
                toReturnArr.add(new DataField(colName, colTypeInGSN));
        }
        toReturn = toReturnArr.toArray(new DataField[] {});
    } finally {
        if (rs != null)
            close(rs);
    }
    return toReturn;
}

From source file:gsn.storage.StorageManager.java

public DataField[] tableToStructureByString(String tableName, Connection connection) throws SQLException {
    StringBuilder sb = new StringBuilder("select * from ").append(tableName).append(" where 1=0 ");
    ResultSet rs = null;/*w w w  . j  ava2s .  c  om*/
    DataField[] toReturn = null;
    try {
        rs = executeQueryWithResultSet(sb, connection);
        ResultSetMetaData structure = rs.getMetaData();
        ArrayList<DataField> toReturnArr = new ArrayList<DataField>();
        for (int i = 1; i <= structure.getColumnCount(); i++) {
            String colName = structure.getColumnLabel(i);
            if (colName.equalsIgnoreCase("pk"))
                continue;
            if (colName.equalsIgnoreCase("timed"))
                continue;
            int colType = structure.getColumnType(i);
            String colTypeName = structure.getColumnTypeName(i);
            int precision = structure.getPrecision(i);
            byte colTypeInGSN = convertLocalTypeToGSN(colType);
            if (colTypeInGSN == -100) {
                logger.error(
                        "The type can't be converted to GSN form - error description: virtual sensor name is: "
                                + tableName + ", field name is: " + colName + ", query is: " + sb);
            }
            if ((colTypeInGSN == DataTypes.VARCHAR) || (colTypeInGSN == DataTypes.CHAR))
                toReturnArr.add(new DataField(colName, colTypeName, precision, colName));
            else
                toReturnArr.add(new DataField(colName, colTypeInGSN));
        }
        toReturn = toReturnArr.toArray(new DataField[] {});
    } finally {
        if (rs != null)
            close(rs);
    }
    return toReturn;
}

From source file:org.talend.core.model.metadata.builder.database.ExtractMetaDataUtils.java

public Integer getMysqlIntMetaDataInfo(ResultSetMetaData rMetadata, int columnIndex) {
    Integer metaDataInfo = new Integer(0);
    try {/*ww  w . jav  a2 s  . co m*/
        metaDataInfo = rMetadata.getPrecision(columnIndex);
    } catch (SQLException e) {
        // log.error(e.toString());
        return metaDataInfo;
    } catch (Exception e) {
        // log.error(e.toString());
        return metaDataInfo;
    }
    return metaDataInfo;
}

From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java

public List<ColumnVO> getColumnsMetaData(String sql) throws Exception {
    Exception error = null;// w  ww.j  av  a2  s  . c om

    List<ColumnVO> tableColumns = new LinkedList<ColumnVO>();

    Connection connection = null;
    PreparedStatement preparedStmnt = null;

    try {
        DataSource dataSource = poolDataSources.get(schemaId);
        connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        preparedStmnt = connection.prepareStatement(sql);
        ResultSet rs = preparedStmnt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            String columnName = rsmd.getColumnName(i);
            String columnType = rsmd.getColumnTypeName(i);
            int columnSqlType = rsmd.getColumnType(i);
            int columnLength = rsmd.getColumnDisplaySize(i);
            int columnPrecision = rsmd.getPrecision(i);

            ColumnVO column = new ColumnVO();
            column.setNameOnTable(columnName);
            column.setType(columnType);
            column.setSqlType(columnSqlType);
            column.setLength(columnLength);
            column.setPrecision(columnPrecision);
            column.setInTable(true);

            tableColumns.add(column);
        }
    } catch (SQLException e) {
        error = e;
    } finally {
        if (preparedStmnt != null) {
            try {
                preparedStmnt.close();
            } catch (SQLException se2) {
                log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage()));
            }
        }
        if (connection != null) {
            try {
                if (error != null) {
                    connection.rollback();
                }
            } catch (SQLException se) {
                log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage()));
            }
            try {
                connection.close();
            } catch (SQLException se) {
                log.warn("Se produjo un error al intentar cerrar la conexin: "
                        .concat(se.getLocalizedMessage()));
            }
        }
    }
    if (error != null) {
        throw error;
    }
    return tableColumns;
}

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

/**
 * @param dbName     ???//from www . j a  v a  2s .co  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: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   ww  w  .  j a  va 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:org.apache.nifi.processors.standard.util.JdbcCommon.java

/**
 * Creates an Avro schema from a result set. If the table/record name is known a priori and provided, use that as a
 * fallback for the record name if it cannot be retrieved from the result set, and finally fall back to a default value.
 *
 * @param rs         The result set to convert to Avro
 * @param recordName The a priori record name to use if it cannot be determined from the result set.
 * @return A Schema object representing the result set converted to an Avro record
 * @throws SQLException if any error occurs during conversion
 *//*from w w w  . j a  v a 2 s. c o  m*/
public static Schema createSchema(final ResultSet rs, String recordName, boolean convertNames)
        throws SQLException {
    final ResultSetMetaData meta = rs.getMetaData();
    final int nrOfColumns = meta.getColumnCount();
    String tableName = StringUtils.isEmpty(recordName) ? "NiFi_ExecuteSQL_Record" : recordName;
    if (nrOfColumns > 0) {
        String tableNameFromMeta = meta.getTableName(1);
        if (!StringUtils.isBlank(tableNameFromMeta)) {
            tableName = tableNameFromMeta;
        }
    }

    if (convertNames) {
        tableName = normalizeNameForAvro(tableName);
    }

    final FieldAssembler<Schema> builder = SchemaBuilder.record(tableName).namespace("any.data").fields();

    /**
     * Some missing Avro types - Decimal, Date types. May need some additional work.
     */
    for (int i = 1; i <= nrOfColumns; i++) {
        /**
        *   as per jdbc 4 specs, getColumnLabel will have the alias for the column, if not it will have the column name.
        *  so it may be a better option to check for columnlabel first and if in case it is null is someimplementation,
        *  check for alias. Postgres is the one that has the null column names for calculated fields.
        */
        String nameOrLabel = StringUtils.isNotEmpty(meta.getColumnLabel(i)) ? meta.getColumnLabel(i)
                : meta.getColumnName(i);
        String columnName = convertNames ? normalizeNameForAvro(nameOrLabel) : nameOrLabel;
        switch (meta.getColumnType(i)) {
        case CHAR:
        case LONGNVARCHAR:
        case LONGVARCHAR:
        case NCHAR:
        case NVARCHAR:
        case VARCHAR:
        case CLOB:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        case BIT:
        case BOOLEAN:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().booleanType().endUnion()
                    .noDefault();
            break;

        case INTEGER:
            if (meta.isSigned(i) || (meta.getPrecision(i) > 0 && meta.getPrecision(i) <= MAX_DIGITS_IN_INT)) {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion()
                        .noDefault();
            } else {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion()
                        .noDefault();
            }
            break;

        case SMALLINT:
        case TINYINT:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().intType().endUnion()
                    .noDefault();
            break;

        case BIGINT:
            // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that.
            // If the precision > 19 (or is negative), use a string for the type, otherwise use a long. The object(s) will be converted
            // to strings as necessary
            int precision = meta.getPrecision(i);
            if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                        .noDefault();
            } else {
                builder.name(columnName).type().unionOf().nullBuilder().endNull().and().longType().endUnion()
                        .noDefault();
            }
            break;

        // java.sql.RowId is interface, is seems to be database
        // implementation specific, let's convert to String
        case ROWID:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        case FLOAT:
        case REAL:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().floatType().endUnion()
                    .noDefault();
            break;

        case DOUBLE:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().doubleType().endUnion()
                    .noDefault();
            break;

        // Did not find direct suitable type, need to be clarified!!!!
        case DECIMAL:
        case NUMERIC:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        // Did not find direct suitable type, need to be clarified!!!!
        case DATE:
        case TIME:
        case TIMESTAMP:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().stringType().endUnion()
                    .noDefault();
            break;

        case BINARY:
        case VARBINARY:
        case LONGVARBINARY:
        case ARRAY:
        case BLOB:
            builder.name(columnName).type().unionOf().nullBuilder().endNull().and().bytesType().endUnion()
                    .noDefault();
            break;

        default:
            throw new IllegalArgumentException("createSchema: Unknown SQL type " + meta.getColumnType(i) + " / "
                    + meta.getColumnTypeName(i) + " (table: " + tableName + ", column: " + columnName
                    + ") cannot be converted to Avro type");
        }
    }

    return builder.endRecord();
}

From source file:org.apache.kylin.rest.service.QueryService.java

/**
 * @param correctedSql/*from w  w  w.ja va  2s  . co  m*/
 * @param sqlRequest
 * @return
 * @throws Exception
 */
private SQLResponse execute(String correctedSql, SQLRequest sqlRequest) throws Exception {
    Connection conn = null;
    Statement stat = null;
    ResultSet resultSet = null;
    Boolean isPushDown = false;

    List<List<String>> results = Lists.newArrayList();
    List<SelectedColumnMeta> columnMetas = Lists.newArrayList();

    try {
        conn = cacheService.getOLAPDataSource(sqlRequest.getProject()).getConnection();

        // special case for prepare query. 
        if (BackdoorToggles.getPrepareOnly()) {
            return getPrepareOnlySqlResponse(correctedSql, conn, isPushDown, results, columnMetas);
        }

        stat = conn.createStatement();
        processStatementAttr(stat, sqlRequest);
        resultSet = stat.executeQuery(correctedSql);

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // Fill in selected column meta
        for (int i = 1; i <= columnCount; ++i) {
            columnMetas.add(new SelectedColumnMeta(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.getCatalogName(i),
                    metaData.getTableName(i), metaData.getPrecision(i), metaData.getScale(i),
                    metaData.getColumnType(i), metaData.getColumnTypeName(i), metaData.isReadOnly(i),
                    metaData.isWritable(i), metaData.isDefinitelyWritable(i)));
        }

        // fill in results
        while (resultSet.next()) {
            List<String> oneRow = Lists.newArrayListWithCapacity(columnCount);
            for (int i = 0; i < columnCount; i++) {
                oneRow.add((resultSet.getString(i + 1)));
            }

            results.add(oneRow);
        }
    } catch (SQLException sqlException) {
        isPushDown = PushDownUtil.doPushDownQuery(sqlRequest.getProject(), correctedSql, results, columnMetas,
                sqlException);
    } finally {
        close(resultSet, stat, conn);
    }

    return getSqlResponse(isPushDown, results, columnMetas);
}

From source file:com.glaf.dts.transform.MxTransformManager.java

@SuppressWarnings("unchecked")
public TableDefinition toTableDefinition(QueryDefinition query, String currentSql) {

    if (query.getId() != null && query.getParentId() != null) {
        query = this.fill(query.getId(), currentSql);
    }//from  w  ww  .j ava 2 s .c o  m

    if (query.getParentId() != null) {
        QueryDefinition parent = this.fill(query.getParentId(), null);
        if (parent != null) {
            logger.debug("parent:" + parent.getTitle());
            logger.debug("resultList:" + parent.getResultList());
            query.setParent(parent);
        }
    }

    String sql = currentSql;
    List<Object> values = null;
    logger.debug("currentSql:" + currentSql);
    if (query.getParentId() != null) {
        if (query.getParent() != null && query.getParent().getResultList() != null
                && !query.getParent().getResultList().isEmpty()) {
            for (Map<String, Object> paramMap : query.getParent().getResultList()) {
                SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, paramMap);
                sql = sqlExecutor.getSql();
                sql = QueryUtils.replaceSQLVars(sql);
                values = (List<Object>) sqlExecutor.getParameter();
                break;
            }
        }
    } else {
        if (sql != null && sql.indexOf("${") != -1) {
            sql = QueryUtils.replaceSQLVars(sql);
            SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, new java.util.HashMap<String, Object>());
            if (sqlExecutor != null) {
                sql = sqlExecutor.getSql();
                sql = QueryUtils.replaceSQLVars(sql);
                values = (List<Object>) sqlExecutor.getParameter();
            }
        }
    }

    logger.debug("sql:" + sql);
    logger.debug("values:" + values);

    TableDefinition table = new TableDefinition();
    Connection conn = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        Database database = databaseService.getDatabaseById(query.getDatabaseId());
        if (database != null) {
            conn = DBConnectionFactory.getConnection(database.getName());
        } else {
            conn = DBConnectionFactory.getConnection();
        }

        sql = QueryUtils.replaceSQLVars(sql);
        psmt = conn.prepareStatement(sql);

        if (values != null && !values.isEmpty()) {
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            int sqlType = rsmd.getColumnType(i);
            ColumnDefinition column = new ColumnDefinition();
            column.setColumnName(rsmd.getColumnName(i));
            column.setColumnLabel(rsmd.getColumnLabel(i));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(i));
            column.setScale(rsmd.getScale(i));
            table.addColumn(column);

            logger.debug("----------------------------------------");
            logger.debug("sqlType:" + sqlType);
            logger.debug("javaType:" + FieldType.getJavaType(sqlType));
            logger.debug("columnName:" + rsmd.getColumnName(i));
            logger.debug("columnTypeName:" + rsmd.getColumnTypeName(i));
            logger.debug("columnClassName:" + rsmd.getColumnClassName(i));
            logger.debug("columnLabel:" + rsmd.getColumnLabel(i));
            logger.debug("columnDisplaySize:" + rsmd.getColumnDisplaySize(i));
            logger.debug("precision:" + rsmd.getPrecision(i));
            logger.debug("scale:" + rsmd.getScale(i));
        }

    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(psmt);
        JdbcUtils.close(conn);
    }
    return table;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public void setColumnSpecificHeaders(Record record, Set<String> knownTableNames, ResultSetMetaData metaData,
        String jdbcNameSpacePrefix) throws SQLException {
    Record.Header header = record.getHeader();
    Set<String> tableNames = new HashSet<>();
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        header.setAttribute(jdbcNameSpacePrefix + metaData.getColumnLabel(i) + ".jdbcType",
                String.valueOf(metaData.getColumnType(i)));

        // Additional headers per various types
        switch (metaData.getColumnType(i)) {
        case Types.DECIMAL:
        case Types.NUMERIC:
            header.setAttribute(jdbcNameSpacePrefix + metaData.getColumnLabel(i) + ".scale",
                    String.valueOf(metaData.getScale(i)));
            header.setAttribute(jdbcNameSpacePrefix + metaData.getColumnLabel(i) + ".precision",
                    String.valueOf(metaData.getPrecision(i)));
            break;
        }//  w w w . j  a v  a 2s. co m

        String tableName = metaData.getTableName(i);

        // Store the column's table name (if not empty)
        if (StringUtils.isNotEmpty(tableName)) {
            tableNames.add(tableName);
        }
    }

    if (tableNames.isEmpty()) {
        tableNames.addAll(knownTableNames);
    }

    header.setAttribute(jdbcNameSpacePrefix + "tables", Joiner.on(",").join(tableNames));
}