Example usage for java.sql Types DECIMAL

List of usage examples for java.sql Types DECIMAL

Introduction

In this page you can find the example usage for java.sql Types DECIMAL.

Prototype

int DECIMAL

To view the source code for java.sql Types DECIMAL.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type DECIMAL.

Usage

From source file:org.jumpmind.db.alter.ModelComparator.java

/**
 * Compares the two columns and returns the changes necessary to create the
 * second column from the first one.//from   w  w  w. jav a 2 s .c o m
 * 
 * @param sourceTable
 *            The source table which contains the source column
 * @param sourceColumn
 *            The source column
 * @param targetTable
 *            The target table which contains the target column
 * @param targetColumn
 *            The target column
 * @return The changes
 */
public List<TableChange> compareColumns(Table sourceTable, Column sourceColumn, Table targetTable,
        Column targetColumn) {
    ArrayList<TableChange> changes = new ArrayList<TableChange>();

    int actualTypeCode = sourceColumn.getMappedTypeCode();
    int desiredTypeCode = targetColumn.getMappedTypeCode();
    boolean sizeMatters = platformInfo.hasSize(targetColumn.getMappedTypeCode());
    boolean scaleMatters = platformInfo.hasPrecisionAndScale(targetColumn.getMappedTypeCode());

    boolean compatible = (actualTypeCode == Types.NUMERIC || actualTypeCode == Types.DECIMAL)
            && (desiredTypeCode == Types.INTEGER || desiredTypeCode == Types.BIGINT);

    if (sourceColumn.isAutoIncrement() && targetColumn.isAutoIncrement()
            && (desiredTypeCode == Types.NUMERIC || desiredTypeCode == Types.DECIMAL)
            && (actualTypeCode == Types.INTEGER || actualTypeCode == Types.BIGINT)) {
        compatible = true;

        // This is the rare case where size doesnt matter!
        sizeMatters = false;
        scaleMatters = false;
    }

    if (!compatible && targetColumn.getMappedTypeCode() != sourceColumn.getMappedTypeCode() && platformInfo
            .getTargetJdbcType(targetColumn.getMappedTypeCode()) != sourceColumn.getMappedTypeCode()) {
        log.debug("The {} column on the {} table changed type codes from {} to {} ",
                new Object[] { sourceColumn.getName(), sourceTable.getName(), sourceColumn.getMappedTypeCode(),
                        targetColumn.getMappedTypeCode() });
        changes.add(new ColumnDataTypeChange(sourceTable, sourceColumn, targetColumn.getMappedTypeCode()));
    }

    String targetSize = targetColumn.getSize();
    if (targetSize == null) {
        Integer defaultSize = platformInfo
                .getDefaultSize(platformInfo.getTargetJdbcType(targetColumn.getMappedTypeCode()));
        if (defaultSize != null) {
            targetSize = defaultSize.toString();
        } else {
            targetSize = "0";
        }
    }
    if (sizeMatters && !StringUtils.equals(sourceColumn.getSize(), targetSize)) {
        log.debug("The {} column on the {} table changed size from ({}) to ({})",
                new Object[] { sourceColumn.getName(), sourceTable.getName(), sourceColumn.getSizeAsInt(),
                        targetColumn.getSizeAsInt() });

        changes.add(new ColumnSizeChange(sourceTable, sourceColumn, targetColumn.getSizeAsInt(),
                targetColumn.getScale()));
    } else if (scaleMatters && (!StringUtils.equals(sourceColumn.getSize(), targetSize) ||
    // ojdbc6.jar returns -127 for the scale of NUMBER that was not given a
    // size or precision
            (!(sourceColumn.getScale() < 0 && targetColumn.getScale() == 0)
                    && sourceColumn.getScale() != targetColumn.getScale()))) {
        log.debug("The {} column on the {} table changed scale from ({},{}) to ({},{})",
                new Object[] { sourceColumn.getName(), sourceTable.getName(), sourceColumn.getSizeAsInt(),
                        sourceColumn.getScale(), targetColumn.getSizeAsInt(), targetColumn.getScale() });
        changes.add(new ColumnSizeChange(sourceTable, sourceColumn, targetColumn.getSizeAsInt(),
                targetColumn.getScale()));
    }

    Object sourceDefaultValue = sourceColumn.getParsedDefaultValue();
    Object targetDefaultValue = targetColumn.getParsedDefaultValue();

    if ((sourceDefaultValue == null && targetDefaultValue != null)
            || (sourceDefaultValue != null && targetDefaultValue == null)
            || (sourceDefaultValue != null && targetDefaultValue != null
                    && !sourceDefaultValue.toString().equals(targetDefaultValue.toString()))) {
        log.debug("The {} column on the {} table changed default value from {} to {} ",
                new Object[] { sourceColumn.getName(), sourceTable.getName(), sourceColumn.getDefaultValue(),
                        targetColumn.getDefaultValue() });
        changes.add(new ColumnDefaultValueChange(sourceTable, sourceColumn, targetColumn.getDefaultValue()));
    }

    if (sourceColumn.isRequired() != targetColumn.isRequired()) {
        log.debug("The {} column on the {} table changed required status from {} to {}",
                new Object[] { sourceColumn.getName(), sourceTable.getName(), sourceColumn.isRequired(),
                        targetColumn.isRequired() });
        changes.add(new ColumnRequiredChange(sourceTable, sourceColumn));
    }

    if (sourceColumn.isAutoIncrement() != targetColumn.isAutoIncrement()) {
        log.debug("The {} column on the {} table changed auto increment status from {} to {} ",
                new Object[] { sourceColumn.getName(), sourceTable.getName(), sourceColumn.isAutoIncrement(),
                        targetColumn.isAutoIncrement() });
        changes.add(new ColumnAutoIncrementChange(sourceTable, sourceColumn));
    }

    return changes;
}

From source file:org.jumpmind.vaadin.ui.common.CommonUiUtils.java

@SuppressWarnings("unchecked")
public static Grid putResultsInGrid(final ResultSet rs, List<Integer> pkcolumns, int maxResultSize,
        final boolean showRowNumbers, String... excludeValues) throws SQLException {

    final Grid grid = new Grid();
    grid.setImmediate(true);//from   w w  w .  j  a v a 2 s.  c om
    grid.setSelectionMode(SelectionMode.MULTI);
    grid.setColumnReorderingAllowed(true);
    grid.setData(new HashMap<Object, List<Object>>());

    final ResultSetMetaData meta = rs.getMetaData();
    int columnCount = meta.getColumnCount();
    grid.addColumn("#", Integer.class).setHeaderCaption("#").setHidable(true);
    Set<String> columnNames = new HashSet<String>();
    Set<Integer> skipColumnIndexes = new HashSet<Integer>();
    int[] types = new int[columnCount];
    for (int i = 1; i <= columnCount; i++) {
        String realColumnName = meta.getColumnName(i);
        String columnName = realColumnName;
        if (!Arrays.asList(excludeValues).contains(columnName)) {

            int index = 1;
            while (columnNames.contains(columnName)) {
                columnName = realColumnName + "_" + index++;
            }
            columnNames.add(columnName);

            Class<?> typeClass = Object.class;
            int type = meta.getColumnType(i);
            types[i - 1] = type;
            switch (type) {
            case Types.FLOAT:
            case Types.DOUBLE:
            case Types.NUMERIC:
            case Types.REAL:
            case Types.DECIMAL:
                typeClass = BigDecimal.class;
                break;
            case Types.TINYINT:
            case Types.SMALLINT:
            case Types.BIGINT:
            case Types.INTEGER:
                typeClass = Long.class;
                break;
            case Types.VARCHAR:
            case Types.CHAR:
            case Types.NVARCHAR:
            case Types.NCHAR:
            case Types.CLOB:
                typeClass = String.class;
            default:
                break;
            }
            Column column = grid.addColumn(columnName, typeClass).setHeaderCaption(columnName).setHidable(true);
            if (typeClass.equals(Long.class)) {
                column.setConverter(new StringToLongConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String convertToPresentation(Long value, Class<? extends String> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        if (value == null) {
                            return NULL_TEXT;
                        } else {
                            return value.toString();
                        }
                    }
                });
            } else if (typeClass.equals(BigDecimal.class)) {
                column.setConverter(new StringToBigDecimalConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public String convertToPresentation(BigDecimal value, Class<? extends String> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        if (value == null) {
                            return NULL_TEXT;
                        } else {
                            return value.toString();
                        }
                    }
                });
            } else {
                column.setConverter(new Converter<String, Object>() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object convertToModel(String value, Class<? extends Object> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        return null;
                    }

                    @Override
                    public String convertToPresentation(Object value, Class<? extends String> targetType,
                            Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException {
                        if (value == null) {
                            return NULL_TEXT;
                        } else {
                            return value.toString();
                        }
                    }

                    @Override
                    public Class<Object> getModelType() {
                        return Object.class;
                    }

                    @Override
                    public Class<String> getPresentationType() {
                        return String.class;
                    }

                });
            }
        } else {
            skipColumnIndexes.add(i - 1);
        }

    }
    int rowNumber = 1;
    while (rs.next() && rowNumber <= maxResultSize) {
        Object[] row = new Object[columnNames.size() + 1];
        row[0] = new Integer(rowNumber);
        int rowIndex = 1;
        for (int i = 0; i < columnCount; i++) {
            if (!skipColumnIndexes.contains(i)) {
                Object o = getObject(rs, i + 1);
                int type = types[i];
                switch (type) {
                case Types.FLOAT:
                case Types.DOUBLE:
                case Types.REAL:
                case Types.NUMERIC:
                case Types.DECIMAL:
                    if (o != null && !(o instanceof BigDecimal)) {
                        o = new BigDecimal(castToNumber(o.toString()));
                    }
                    break;
                case Types.TINYINT:
                case Types.SMALLINT:
                case Types.BIGINT:
                case Types.INTEGER:
                    if (o != null && !(o instanceof Long)) {
                        o = new Long(castToNumber(o.toString()));
                    }
                    break;
                default:
                    break;
                }
                List<Object> primaryKeys = new ArrayList<Object>();
                for (Integer pkcolumn : pkcolumns) {
                    primaryKeys.add(getObject(rs, pkcolumn + 1));
                }
                ((HashMap<Object, List<Object>>) grid.getData()).put(o, primaryKeys);
                row[rowIndex] = o;
                rowIndex++;
            }
        }
        grid.addRow(row);
        rowNumber++;
    }

    if (rowNumber < 100) {
        grid.getColumn("#").setWidth(75);
    } else if (rowNumber < 1000) {
        grid.getColumn("#").setWidth(95);
    } else {
        grid.getColumn("#").setWidth(115);
    }

    if (!showRowNumbers) {
        grid.getColumn("#").setHidden(true);
    } else {
        grid.setFrozenColumnCount(1);
    }

    return grid;
}

From source file:dao.MetricsDAO.java

public static String updateMetricValues(int id, Map<String, String[]> params) {
    String message = "Internal error";
    if (params == null || params.size() == 0) {
        return "Empty post body";
    }/*  w  w w  .j  a v  a  2 s .co m*/

    boolean needAnd = false;
    String setClause = "";
    String description = "";
    String[] descArray = null;
    List<Object> args = new ArrayList<Object>();
    List<Integer> argTypes = new ArrayList<Integer>();

    if (params.containsKey(MetricRowMapper.METRIC_DESCRIPTION_COLUMN)) {
        descArray = params.get(MetricRowMapper.METRIC_DESCRIPTION_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DESCRIPTION)) {
        descArray = params.get(MetricRowMapper.METRIC_MODULE_DESCRIPTION);
    }

    if (descArray != null && descArray.length > 0) {
        description = descArray[0];
        setClause += MetricRowMapper.METRIC_DESCRIPTION_COLUMN + " = ? ";
        needAnd = true;
        args.add(description);
        argTypes.add(Types.VARCHAR);
    }

    String dashboard = "";
    String[] dashboardArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN)) {
        dashboardArray = params.get(MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DASHBOARD_NAME)) {
        dashboardArray = params.get(MetricRowMapper.METRIC_MODULE_DASHBOARD_NAME);
    }

    if (dashboardArray != null && dashboardArray.length > 0) {
        dashboard = dashboardArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_DASHBOARD_NAME_COLUMN + " = ? ";
        needAnd = true;
        args.add(dashboard);
        argTypes.add(Types.VARCHAR);
    }

    String type = "";
    String[] typeArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN)) {
        typeArray = params.get(MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_REF_ID_TYPE)) {
        typeArray = params.get(MetricRowMapper.METRIC_MODULE_REF_ID_TYPE);
    }

    if (typeArray != null && typeArray.length > 0) {
        type = typeArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_REF_ID_TYPE_COLUMN + " = ? ";
        needAnd = true;
        args.add(type);
        argTypes.add(Types.VARCHAR);
    }
    String grain = "";
    String[] grainArray = null;

    if (params.containsKey(MetricRowMapper.METRIC_GRAIN_COLUMN)) {
        grainArray = params.get(MetricRowMapper.METRIC_GRAIN_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_GRAIN)) {
        grainArray = params.get(MetricRowMapper.METRIC_MODULE_GRAIN);
    }

    if (grainArray != null && grainArray.length > 0) {
        grain = grainArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_GRAIN_COLUMN + " = ? ";
        needAnd = true;
        args.add(grain);
        argTypes.add(Types.VARCHAR);
    }

    String formula = "";
    String[] formulaArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_FORMULA_COLUMN)) {
        formulaArray = params.get(MetricRowMapper.METRIC_FORMULA_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_FORMULA)) {
        formulaArray = params.get(MetricRowMapper.METRIC_MODULE_FORMULA);
    }

    if (formulaArray != null && formulaArray.length > 0) {
        formula = formulaArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_FORMULA_COLUMN + " = ? ";
        needAnd = true;
        args.add(formula);
        argTypes.add(Types.VARCHAR);
    }

    String displayFactorString = "";
    Double displayFactor = 0.0;
    String[] displayFactorArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_DISPLAY_FACTOR_COLUMN)) {
        displayFactorArray = params.get(MetricRowMapper.METRIC_DISPLAY_FACTOR_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR)) {
        displayFactorArray = params.get(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR);
    }

    if (displayFactorArray != null && displayFactorArray.length > 0) {
        displayFactorString = displayFactorArray[0];
        try {
            displayFactor = Double.parseDouble(displayFactorString);
            if (needAnd) {
                setClause += ", ";
            }
            setClause += MetricRowMapper.METRIC_DISPLAY_FACTOR_COLUMN + " = ? ";
            needAnd = true;
            args.add(displayFactor);
            argTypes.add(Types.DECIMAL);
        } catch (NumberFormatException e) {
            Logger.error("MetricDAO updateMetricValues wrong page parameter. Error message: " + e.getMessage());
            displayFactor = 0.0;
        }
    }

    String displayFactorSym = "";
    String[] factorSymArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_DISPLAY_FACTOR_SYM_COLUMN)) {
        factorSymArray = params.get(MetricRowMapper.METRIC_DISPLAY_FACTOR_SYM_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR_SYM)) {
        factorSymArray = params.get(MetricRowMapper.METRIC_MODULE_DISPLAY_FACTOR_SYM);
    }

    if (factorSymArray != null && factorSymArray.length > 0) {
        displayFactorSym = factorSymArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_DISPLAY_FACTOR_SYM_COLUMN + " = ? ";
        needAnd = true;
        args.add(displayFactorSym);
        argTypes.add(Types.VARCHAR);
    }

    String groupSkString = "";
    Integer groupSk = 0;
    String[] groupSkArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_SUB_CATEGORY_COLUMN)) {
        groupSkArray = params.get(MetricRowMapper.METRIC_SUB_CATEGORY_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_SUB_CATEGORY)) {
        groupSkArray = params.get(MetricRowMapper.METRIC_MODULE_SUB_CATEGORY);
    }

    if (groupSkArray != null && groupSkArray.length > 0) {
        groupSkString = groupSkArray[0];
        try {
            groupSk = Integer.parseInt(groupSkString);
            if (needAnd) {
                setClause += ", ";
            }
            setClause += MetricRowMapper.METRIC_SUB_CATEGORY_COLUMN + " = ? ";
            needAnd = true;
            args.add(groupSk);
            argTypes.add(Types.INTEGER);
        } catch (NumberFormatException e) {
            Logger.error("MetricDAO updateMetricValues wrong page parameter. Error message: " + e.getMessage());
            groupSk = 0;
        }
    }

    String metricSource = "";
    String[] metricSourceArray = null;
    if (params.containsKey(MetricRowMapper.METRIC_SOURCE_COLUMN)) {
        metricSourceArray = params.get(MetricRowMapper.METRIC_SOURCE_COLUMN);
    } else if (params.containsKey(MetricRowMapper.METRIC_MODULE_SOURCE)) {
        metricSourceArray = params.get(MetricRowMapper.METRIC_MODULE_SOURCE);
    }

    if (metricSourceArray != null && metricSourceArray.length > 0) {
        metricSource = metricSourceArray[0];
        if (needAnd) {
            setClause += ", ";
        }
        setClause += MetricRowMapper.METRIC_SOURCE_COLUMN + " = ? ";
        needAnd = true;
        args.add(metricSource);
        argTypes.add(Types.VARCHAR);
    }

    if (StringUtils.isNotBlank(setClause)) {
        args.add(id);
        argTypes.add(Types.SMALLINT);
        int row = getJdbcTemplate().update(UPDATE_METRIC.replace("$SET_CLAUSE", setClause), args.toArray(),
                Ints.toArray(argTypes));
        if (row > 0) {
            message = "";
        }
    } else {
        message = "Wrong post body";
    }
    return message;
}

From source file:com.streamsets.pipeline.stage.processor.parser.sql.SqlParserProcessor.java

private void resolveSchema(SchemaAndTable schemaAndTable) throws StageException {
    Map<String, Integer> columns = new HashMap<>();
    String schema = schemaAndTable.getSchema();
    String table = schemaAndTable.getTable();
    try (Statement s = connection.createStatement()) {
        ResultSetMetaData md = s//from ww  w. j av a2s .  c o  m
                .executeQuery(Utils.format("SELECT * FROM {}{} WHERE 1 = 0",
                        StringUtils.isNotEmpty(schema) ? "\"" + schema + "\"." : "", "\"" + table + "\""))
                .getMetaData();
        int colCount = md.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            int colType = md.getColumnType(i);
            String colName = md.getColumnName(i);
            if (!configBean.caseSensitive) {
                colName = colName.toUpperCase();
            }
            if (colType == Types.DATE || colType == Types.TIME || colType == Types.TIMESTAMP) {
                dateTimeColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                dateTimeColumns.get(schemaAndTable).put(colName, md.getColumnTypeName(i));
            }

            if (colType == Types.DECIMAL || colType == Types.NUMERIC) {
                decimalColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>()).put(colName,
                        new PrecisionAndScale(md.getPrecision(i), md.getScale(i)));
            }
            columns.put(md.getColumnName(i), md.getColumnType(i));
        }
        tableSchemas.put(schemaAndTable, columns);
    } catch (SQLException ex) {
        throw new StageException(JDBC_00, configBean.hikariConfigBean.connectionString);
    }
}

From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java

private boolean calculateBatchQuerySupport() throws DataServiceFault {
    Object[] resultMap;//from ww w. j ava 2  s . c o  m
    List<Connection> connections = new ArrayList<Connection>();
    if (this.getConfig().hasJDBCBatchUpdateSupport()) {
        if (this.getQueryType() == SQLQuery.DS_QUERY_TYPE_STORED_PROC) {
            try {
                resultMap = this.getStoredProcFuncProps(this.extractStoredProcName(true));
                ResultSet rs = (ResultSet) resultMap[1];
                connections.add((Connection) resultMap[0]);
                if (!rs.next()) {
                    resultMap = this.getStoredProcFuncProps(this.extractStoredProcName(false));
                    rs = (ResultSet) resultMap[1];
                    connections.add((Connection) resultMap[0]);
                    if (!rs.next()) {
                        throw new DataServiceFault("Cannot find metadata for the stored procedure");
                    }
                }
                /*
                 * stored procedures here can only have IN params and
                 * results which only returns an integer, which has the
                 * update count, all other situations are not supported for
                 * batch updates
                 */
                StoredProcMetadataCollection mdCollection = new StoredProcMetadataCollection(rs);
                for (StoredProcMetadataEntry entry : mdCollection.getEntries()) {
                    switch (entry.getColumnReturn()) {
                    case DatabaseMetaData.procedureColumnIn:
                        break;
                    case DatabaseMetaData.procedureColumnReturn:
                        if (!(entry.getColumnDataType() == Types.INTEGER
                                || entry.getColumnDataType() == Types.BIGINT
                                || entry.getColumnDataType() == Types.DECIMAL)) {
                            return false;
                        }
                        break;
                    default:
                        return false;
                    }
                }
                return true;
            } catch (Throwable e) {
                throw new DataServiceFault("Error in retrieving database metadata.");
            } finally {
                for (Connection aCon : connections) {
                    try {
                        aCon.close();
                    } catch (SQLException ignore) {
                    }
                }
            }
        } else {
            return true;
        }
    } else {
        return false;
    }
}

From source file:org.executequery.gui.importexport.AbstractImportExportWorker.java

/**
 * Sets the specified value in the specified position for the
 * specified java.sql.Type within the prepared statement.
 *
 * @param value - the value// w  w w  . j ava2  s .com
 * @param index - the position within the statement
 * @param sqlType - the SQL type
 * @param trim - whether to trim the whitespace from the value
 * @param df - the DataFormat object for date values
 */
protected void setValue(String value, int index, int sqlType, boolean trim, DateFormat df) throws Exception {

    if (value == null) {

        prepStmnt.setNull(index, sqlType);

    } else {

        switch (sqlType) {

        case Types.TINYINT:
            byte _byte = Byte.valueOf(value).byteValue();
            prepStmnt.setShort(index, _byte);
            break;

        case Types.BIGINT:
            long _long = Long.valueOf(value).longValue();
            prepStmnt.setLong(index, _long);
            break;

        case Types.SMALLINT:
            short _short = Short.valueOf(value).shortValue();
            prepStmnt.setShort(index, _short);
            break;

        case Types.LONGVARCHAR:
        case Types.CHAR:
        case Types.VARCHAR:
            if (trim) {
                value = value.trim();
            }
            prepStmnt.setString(index, value);
            break;

        case Types.BIT:
        case Types.BOOLEAN:

            String booleanValue = value;
            if ("t".equalsIgnoreCase(value)) {

                booleanValue = "true";

            } else if ("f".equalsIgnoreCase(value)) {

                booleanValue = "false";
            }

            boolean _boolean = Boolean.valueOf(booleanValue).booleanValue();
            prepStmnt.setBoolean(index, _boolean);
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
            prepStmnt.setBigDecimal(index, new BigDecimal(value));
            break;

        case Types.REAL:
            float _float = Float.valueOf(value).floatValue();
            prepStmnt.setFloat(index, _float);
            break;

        case Types.FLOAT:
        case Types.DOUBLE:
            prepStmnt.setDouble(index, Double.parseDouble(value));
            break;

        case Types.INTEGER:
            prepStmnt.setInt(index, Integer.parseInt(value));
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            // if the date format is null, insert as a char value
            if (df != null) {
                java.util.Date j_datetime = df.parse(value);
                prepStmnt.setDate(index, new java.sql.Date(j_datetime.getTime()));
            } else {
                try {
                    prepStmnt.setObject(index, value, sqlType);
                    /*
                    if (sqlType == Types.TIMESTAMP) {
                        prepStmnt.setTimestamp(index,
                                java.sql.Timestamp.valueOf(value));
                    }
                    else if (sqlType == Types.TIME) {
                        prepStmnt.setTime(index,
                                java.sql.Time.valueOf(value));
                    }
                    else {
                        prepStmnt.setDate(index,
                                java.sql.Date.valueOf(value));
                    }
                     */
                }
                // want a more useful message here than what will likely
                // be returned due to internal driver code on formatting
                // a SQL date value from string
                // (ie. could be parsing error, number format etc...)
                catch (Exception e) {
                    throw new IllegalArgumentException("[ " + MiscUtils.getExceptionName(e) + " ] "
                            + getBundle().getString("AbstractImportExportWorker.dateConversionError"));
                }

            }
            break;

        case Types.LONGVARBINARY:
        case Types.BINARY:
        case Types.BLOB:
        case Types.CLOB:
            prepStmnt.setBytes(index, Base64.decode(value));
            break;

        default:
            prepStmnt.setObject(index, value);
            break;
        }
    }
}

From source file:com.mapd.utility.SQLImporter.java

private String getColType(int cType, int precision, int scale) {
    if (precision > 19) {
        precision = 19;/*from w w w.j av a2s. co  m*/
    }
    if (scale > 19) {
        scale = 18;
    }
    switch (cType) {
    case java.sql.Types.TINYINT:
    case java.sql.Types.SMALLINT:
        return ("SMALLINT");
    case java.sql.Types.INTEGER:
        return ("INTEGER");
    case java.sql.Types.BIGINT:
        return ("BIGINT");
    case java.sql.Types.FLOAT:
        return ("FLOAT");
    case java.sql.Types.DECIMAL:
        return ("DECIMAL(" + precision + "," + scale + ")");
    case java.sql.Types.DOUBLE:
        return ("DOUBLE");
    case java.sql.Types.REAL:
        return ("REAL");
    case java.sql.Types.NUMERIC:
        return ("NUMERIC(" + precision + "," + scale + ")");
    case java.sql.Types.TIME:
        return ("TIME");
    case java.sql.Types.TIMESTAMP:
        return ("TIMESTAMP");
    case java.sql.Types.DATE:
        return ("DATE");
    case java.sql.Types.BOOLEAN:
    case java.sql.Types.BIT: // deal with postgress treating boolean as bit... this will bite me
        return ("BOOLEAN");
    case java.sql.Types.NVARCHAR:
    case java.sql.Types.VARCHAR:
    case java.sql.Types.NCHAR:
    case java.sql.Types.CHAR:
    case java.sql.Types.LONGVARCHAR:
    case java.sql.Types.LONGNVARCHAR:
        return ("TEXT ENCODING DICT");
    default:
        throw new AssertionError("Column type " + cType + " not Supported");
    }
}

From source file:org.apache.oozie.command.SchemaCheckXCommand.java

private String getSQLTypeFromInt(int t) {
    switch (t) {/*from ww  w.  j  a va2s  .c  o  m*/
    case Types.BIT:
        return "BIT";
    case Types.TINYINT:
        return "TINYINT";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.BIGINT:
        return "BIGINT";
    case Types.FLOAT:
        return "FLOAT";
    case Types.REAL:
        return "REAL";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.CHAR:
        return "CHAR";
    case Types.VARCHAR:
        return "VARCHAR";
    case Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case Types.DATE:
        return "DATE";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.BINARY:
        return "BINARY";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.NULL:
        return "NULL";
    case Types.OTHER:
        return "OTHER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.DISTINCT:
        return "DISTINCT";
    case Types.STRUCT:
        return "STRUCT";
    case Types.ARRAY:
        return "ARRAY";
    case Types.BLOB:
        return "BLOB";
    case Types.CLOB:
        return "CLOB";
    case Types.REF:
        return "REF";
    case Types.DATALINK:
        return "DATALINK";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.ROWID:
        return "ROWID";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.SQLXML:
        return "SQLXML";
    default:
        return "unknown";
    }
}

From source file:funcoes.funcoes.java

@SuppressWarnings("rawtypes")
public static Vector<Comparable> proximaLinha(ResultSet rs, ResultSetMetaData rsmd) throws SQLException {
    Vector<Comparable> LinhaAtual = new Vector<Comparable>();

    try {/*from  w  w w.  ja va 2 s.  co m*/
        for (int i = 1; i <= rsmd.getColumnCount(); ++i) {
            switch (rsmd.getColumnType(i)) {

            case Types.VARCHAR:
                LinhaAtual.addElement(rs.getString(i));
                break;
            case Types.TIMESTAMP:
                LinhaAtual.addElement(rs.getDate(i).toLocaleString().substring(0, 10));
                break;
            case Types.INTEGER:
                LinhaAtual.addElement(rs.getInt(i));
                break;
            case Types.DECIMAL:
                LinhaAtual.addElement(funcoes.paraFormatoDinheiro(rs.getDouble(i)));
                break;
            case Types.DOUBLE:
                LinhaAtual.addElement(funcoes.paraFormatoDinheiro(rs.getDouble(i)));
                break;

            }
        }
    } catch (SQLException e) {
    }
    return LinhaAtual;

}

From source file:jongo.jdbc.JDBCExecutor.java

/**
 * Utility method which registers in a CallableStatement object the different {@link jongo.jdbc.StoredProcedureParam}
 * instances in the given list. Returns a List of {@link jongo.jdbc.StoredProcedureParam} with all the OUT parameters
 * registered in the CallableStatement/*from   w  w w .  j  a  v a2 s .  c o m*/
 * @param cs the CallableStatement object where the parameters are registered.
 * @param params a list of {@link jongo.jdbc.StoredProcedureParam}
 * @return a list of OUT {@link jongo.jdbc.StoredProcedureParam} 
 * @throws SQLException if we fail to register any of the parameters in the CallableStatement
 */
private static List<StoredProcedureParam> addParameters(final CallableStatement cs,
        final List<StoredProcedureParam> params) throws SQLException {
    List<StoredProcedureParam> outParams = new ArrayList<StoredProcedureParam>();
    int i = 1;
    for (StoredProcedureParam p : params) {
        final Integer sqlType = p.getType();
        if (p.isOutParameter()) {
            l.debug("Adding OUT parameter " + p.toString());
            cs.registerOutParameter(i++, sqlType);
            outParams.add(p);
        } else {
            l.debug("Adding IN parameter " + p.toString());
            switch (sqlType) {
            case Types.BIGINT:
            case Types.INTEGER:
            case Types.TINYINT:
                //                    case Types.NUMERIC:
                cs.setInt(i++, Integer.valueOf(p.getValue()));
                break;
            case Types.DATE:
                cs.setDate(i++, (Date) JongoUtils.parseValue(p.getValue()));
                break;
            case Types.TIME:
                cs.setTime(i++, (Time) JongoUtils.parseValue(p.getValue()));
                break;
            case Types.TIMESTAMP:
                cs.setTimestamp(i++, (Timestamp) JongoUtils.parseValue(p.getValue()));
                break;
            case Types.DECIMAL:
                cs.setBigDecimal(i++, (BigDecimal) JongoUtils.parseValue(p.getValue()));
                break;
            case Types.DOUBLE:
                cs.setDouble(i++, Double.valueOf(p.getValue()));
                break;
            case Types.FLOAT:
                cs.setLong(i++, Long.valueOf(p.getValue()));
                break;
            default:
                cs.setString(i++, p.getValue());
                break;
            }
        }
    }
    return outParams;
}