Example usage for java.sql ResultSetMetaData getScale

List of usage examples for java.sql ResultSetMetaData getScale

Introduction

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

Prototype

int getScale(int column) throws SQLException;

Source Link

Document

Gets the designated column's number of digits to right of the decimal point.

Usage

From source file:jongo.handler.ResultSetMetaDataHandler.java

@Override
public List<Row> handle(ResultSet rs) throws SQLException {
    List<Row> results = new ArrayList<Row>();
    int rowId = 0;
    ResultSetMetaData metaData = rs.getMetaData();
    Map<String, String> map = null;
    for (int i = 1; i <= metaData.getColumnCount(); i++) {
        map = new HashMap<String, String>(2);
        map.put("tableName", metaData.getTableName(i));
        map.put("columnName", metaData.getColumnName(i));
        map.put("columnLabel", metaData.getColumnLabel(i));
        map.put("columnType", metaData.getColumnTypeName(i));
        map.put("columnSize", String.valueOf(metaData.getColumnDisplaySize(i)));
        map.put("precision", String.valueOf(metaData.getPrecision(i)));
        map.put("scale", String.valueOf(metaData.getScale(i)));

        //            map.put("catalog_name", metaData.getCatalogName(i));
        //            map.put("column_class_name", metaData.getColumnClassName(i));
        //            map.put("schema_name", metaData.getSchemaName(i));
        //            map.put("column_type", String.valueOf(metaData.getColumnType(i)));

        if (map != null)
            results.add(new Row(rowId++, map));
    }//from  ww w. ja va 2 s .co  m
    return results;
}

From source file:com.healthmarketscience.jackcess.ImportUtil.java

/**
 * Copy an existing JDBC ResultSet into a new (or optionally existing) table
 * in this database.//from w  w w. j ava  2s. c o  m
 * 
 * @param name Name of the new table to create
 * @param source ResultSet to copy from
 * @param filter valid import filter
 * @param useExistingTable if {@code true} use current table if it already
 *                         exists, otherwise, create new table with unique
 *                         name
 *
 * @return the name of the imported table
 * 
 * @see Builder
 */
public static String importResultSet(ResultSet source, Database db, String name, ImportFilter filter,
        boolean useExistingTable) throws SQLException, IOException {
    ResultSetMetaData md = source.getMetaData();

    name = Database.escapeIdentifier(name);
    Table table = null;
    if (!useExistingTable || ((table = db.getTable(name)) == null)) {

        List<Column> columns = new LinkedList<Column>();
        for (int i = 1; i <= md.getColumnCount(); i++) {
            Column column = new Column();
            column.setName(Database.escapeIdentifier(md.getColumnName(i)));
            int lengthInUnits = md.getColumnDisplaySize(i);
            column.setSQLType(md.getColumnType(i), lengthInUnits);
            DataType type = column.getType();
            // we check for isTrueVariableLength here to avoid setting the length
            // for a NUMERIC column, which pretends to be var-len, even though it
            // isn't
            if (type.isTrueVariableLength() && !type.isLongValue()) {
                column.setLengthInUnits((short) lengthInUnits);
            }
            if (type.getHasScalePrecision()) {
                int scale = md.getScale(i);
                int precision = md.getPrecision(i);
                if (type.isValidScale(scale)) {
                    column.setScale((byte) scale);
                }
                if (type.isValidPrecision(precision)) {
                    column.setPrecision((byte) precision);
                }
            }
            columns.add(column);
        }

        table = createUniqueTable(db, name, columns, md, filter);
    }

    List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE);
    int numColumns = md.getColumnCount();

    while (source.next()) {
        Object[] row = new Object[numColumns];
        for (int i = 0; i < row.length; i++) {
            row[i] = source.getObject(i + 1);
        }
        row = filter.filterRow(row);
        if (row == null) {
            continue;
        }
        rows.add(row);
        if (rows.size() == COPY_TABLE_BATCH_SIZE) {
            table.addRows(rows);
            rows.clear();
        }
    }
    if (rows.size() > 0) {
        table.addRows(rows);
    }

    return table.getName();
}

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

/**
 * Convert from JDBC metadata to Avatica columns.
 *///from  w w  w.j  a v  a2s.  c  o 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.taobao.tddl.common.jdbc.MetaDataQueryForMapHandler.java

/**
 * @param tableName //w ww  .  j av  a  2  s  .c o  m
 */
private void initMetaData(String tableName, ResultSetMetaData rsmd) {
    try {
        int columnCount = rsmd.getColumnCount();
        String[] columnNames = new String[columnCount];
        ColumnMetaData[] columns = new ColumnMetaData[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columnNames[i - 1] = rsmd.getColumnName(i).toLowerCase();
            int sqlType = rsmd.getColumnType(i);
            if (sqlType == java.sql.Types.DATE) {
                sqlType = java.sql.Types.TIMESTAMP;
            }
            int scale = rsmd.getScale(i);
            String className = rsmd.getColumnClassName(i);
            columns[i - 1] = new ColumnMetaData(sqlType, scale, className);
        }
        TableMetaData tmd = new TableMetaData(columnNames, columns);
        this.tableMetaDatas.putIfAbsent(tableName, tmd);
    } catch (SQLException e) {
        log.warn("Fetch Metadata from resultSet failed.", e);
    }
}

From source file:org.apache.kylin.rest.util.HiveReroute.java

private void extractColumnMetadata(ResultSet resultSet, List<SelectedColumnMeta> columnMetas)
        throws SQLException {
    ResultSetMetaData metaData = null;
    int columnCount = 0;

    metaData = resultSet.getMetaData();//from  w w w  . j a va 2  s  .  c  o  m
    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), false,
                metaData.isCurrency(i), metaData.isNullable(i), false, metaData.getColumnDisplaySize(i),
                metaData.getColumnLabel(i), metaData.getColumnName(i), null, null, null,
                metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i),
                metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false));
    }
}

From source file:org.apache.kylin.rest.adhoc.AdHocRunnerJdbcImpl.java

@Override
public void executeQuery(String query, List<List<String>> results, List<SelectedColumnMeta> columnMetas)
        throws Exception {
    Statement statement = null;/*from  w w w  .  j  ava 2s . c  om*/
    Connection connection = this.getConnection();
    ResultSet resultSet = null;

    try {
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);
        extractResults(resultSet, results);
    } catch (SQLException sqlException) {
        throw sqlException;
    }

    //extract column metadata
    ResultSetMetaData metaData = null;
    int columnCount = 0;
    try {
        metaData = resultSet.getMetaData();
        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),
                    false, metaData.isCurrency(i), metaData.isNullable(i), false,
                    metaData.getColumnDisplaySize(i), metaData.getColumnLabel(i), metaData.getColumnName(i),
                    null, null, null, metaData.getPrecision(i), metaData.getScale(i), metaData.getColumnType(i),
                    metaData.getColumnTypeName(i), metaData.isReadOnly(i), false, false));
        }

    } catch (SQLException sqlException) {
        throw sqlException;
    }

    closeConnection(connection);
}

From source file:org.ralasafe.db.DBView.java

private static TableView getTable(Connection conn, String dsName, String schema, String tableName)
        throws SQLException {
    String mySchema = "";
    if (!StringUtil.isEmpty(schema)) {
        mySchema = schema + ".";
    }/*from   w  w w .j  a va 2 s  .  c o m*/

    if (log.isDebugEnabled()) {
        log.debug("Get table/view definition: dsName=" + dsName + ", table/view Name=" + mySchema + tableName);
    }

    Statement stmt = null;
    ResultSet rs = null;
    ResultSet primaryKeys = null;

    try {
        stmt = conn.createStatement();

        rs = stmt.executeQuery("select * from " + mySchema + tableName + " where 1=2");
        ResultSetMetaData metaData = rs.getMetaData();

        TableView table = new TableView();
        table.setSchema(schema);
        table.setName(tableName);

        DatabaseMetaData metaData2 = conn.getMetaData();
        String databaseProductName = DBUtil.getDatabaseProductName(conn);

        if (databaseProductName == DBUtil.MYSQL) {
            primaryKeys = metaData2.getPrimaryKeys(schema, null, tableName);
        } else {
            primaryKeys = metaData2.getPrimaryKeys(null, null, tableName);
        }

        Map pkColumnViewMap = new HashMap();
        while (primaryKeys.next()) {
            pkColumnViewMap.put(primaryKeys.getString("COLUMN_NAME"), null);
        }

        List columnList = new ArrayList(metaData.getColumnCount());
        for (int i = 1, columnCount = metaData.getColumnCount(); i <= columnCount; i++) {
            ColumnView column = new ColumnView();
            String columnName = metaData.getColumnName(i);
            column.setName(columnName);
            String sqlType = metaData.getColumnTypeName(i);

            if (sqlType.equalsIgnoreCase("blob") || sqlType.equalsIgnoreCase("clob")
                    || sqlType.equalsIgnoreCase("text")) {
                // DO NOTHING
            } else {
                int precision = metaData.getPrecision(i);
                int scale = metaData.getScale(i);

                if (precision != 0) {
                    if (scale == 0) {
                        sqlType = sqlType + "(" + precision + ")";
                    } else {
                        sqlType = sqlType + "(" + precision + "," + scale + ")";
                    }
                }
            }
            column.setSqlType(sqlType);
            columnList.add(column);

            // it's a primary key?
            if (pkColumnViewMap.containsKey(columnName)) {
                pkColumnViewMap.put(columnName, column);
            }
        }

        table.setColumnViews(columnList);

        // sometimes, oracle jdbc driver returns pk info is redundance, 
        // actually the column does exist at all.  Clear them.
        clearInvalidPK(pkColumnViewMap);

        if (pkColumnViewMap.size() > 0) {
            table.setPkColumnViews(pkColumnViewMap.values());
        }
        return table;
    } finally {
        DBUtil.close(primaryKeys);
        DBUtil.close(rs);
        DBUtil.close(stmt);
    }
}

From source file:ro.nextreports.engine.util.QueryUtil.java

public List<NameType> executeQueryForColumnNames(String sql) throws Exception {
    // long t = System.currentTimeMillis();
    StringWriter sw = new StringWriter(100);
    // sw.append("SELECT * FROM (");
    sw.append(sql);//from  ww w.jav  a  2  s. c  om
    // sw.append(") A WHERE 1 = -1");

    String sqlForHeader = sw.toString();
    LOG.info("call for header columns = " + sqlForHeader);

    ResultSet rs = null;
    Statement stmt = null;
    try {
        if (isProcedureCall(sqlForHeader)) {
            Dialect dialect = DialectUtil.getDialect(con);
            CallableStatement cs = con.prepareCall("{" + sqlForHeader + "}");
            stmt = cs;
            if (dialect.hasProcedureWithCursor()) {
                cs.registerOutParameter(1, dialect.getCursorSqlType());
            }
            rs = cs.executeQuery();
            if (dialect.hasProcedureWithCursor()) {
                rs = (ResultSet) (cs.getObject(1));
            }
        } else {
            stmt = con.createStatement();
            stmt.setMaxRows(1);
            rs = stmt.executeQuery(sqlForHeader);
        }
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();

        List<NameType> columnNames = new ArrayList<NameType>();
        for (int i = 0; i < columnCount; i++) {
            columnNames.add(new NameType(rsmd.getColumnLabel(i + 1), dialect.getJavaType(
                    rsmd.getColumnTypeName(i + 1), rsmd.getPrecision(i + 1), rsmd.getScale(i + 1))));
            // rsmd.getColumnClassName(i + 1)));
        }

        // t = System.currentTimeMillis() - t;
        // System.out.println("execute query for column names in " + t +
        // "ms");

        return columnNames;
    } finally {
        ConnectionUtil.closeResultSet(rs);
        ConnectionUtil.closeStatement(stmt);
    }

}

From source file:org.apache.sqoop.connector.jdbc.oracle.util.OracleQueries.java

public static List<Column> getColDataTypes(Connection connection, OracleTable table, List<String> colNames)
        throws SQLException {
    List<Column> result = new ArrayList<Column>();
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT ");
    for (int idx = 0; idx < colNames.size(); idx++) {
        if (idx > 0) {
            sb.append(",");
        }//from   w w  w  .  ja v a  2s . co  m
        sb.append(colNames.get(idx));
    }
    sb.append(String.format(" FROM %s WHERE 0=1", table.toString()));

    String sql = sb.toString();
    PreparedStatement statement = connection.prepareStatement(sql);
    try {
        ResultSetMetaData metadata = statement.getMetaData();
        int numCols = metadata.getColumnCount();
        for (int i = 1; i < numCols + 1; i++) {
            String colName = metadata.getColumnName(i);
            Column oracleColumn = OracleSqlTypesUtils.sqlTypeToSchemaType(metadata.getColumnType(i), colName,
                    metadata.getPrecision(i), metadata.getScale(i));

            result.add(oracleColumn);
        }
    } finally {
        statement.close();
    }
    return result;
}

From source file:org.apache.sqoop.connector.hbase.HbaseToInitializer.java

@Override
public Schema getSchema(InitializerContext context, LinkConfiguration linkConfig,
        ToJobConfiguration toJobConfig) {
    executor = new HbaseExecutor(linkConfig.linkConfig);

    String schemaName = toJobConfig.toJobConfig.tableName;

    if (schemaName == null) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0019,
                "Table name extraction not supported yet.");
    }//  w w  w.  j a v a2 s.  c om

    if (toJobConfig.toJobConfig.schemaName != null) {
        schemaName = toJobConfig.toJobConfig.schemaName + "." + schemaName;
    }

    Schema schema = new Schema(schemaName);
    ResultSet rs = null;
    ResultSetMetaData rsmt = null;
    try {
        rs = executor.executeQuery("SELECT * FROM " + schemaName + " WHERE 1 = 0");

        rsmt = rs.getMetaData();
        for (int i = 1; i <= rsmt.getColumnCount(); i++) {
            String columnName = rsmt.getColumnName(i);

            if (StringUtils.isEmpty(columnName)) {
                columnName = rsmt.getColumnLabel(i);
                if (StringUtils.isEmpty(columnName)) {
                    columnName = "Column " + i;
                }
            }

            Column column = SqlTypesUtils.sqlTypeToSchemaType(rsmt.getColumnType(i), columnName,
                    rsmt.getPrecision(i), rsmt.getScale(i));
            schema.addColumn(column);
        }

        return schema;
    } catch (SQLException e) {
        throw new SqoopException(GenericJdbcConnectorError.GENERIC_JDBC_CONNECTOR_0016, e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.info("Ignoring exception while closing ResultSet", e);
            }
        }
    }
}