Example usage for java.sql Types NUMERIC

List of usage examples for java.sql Types NUMERIC

Introduction

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

Prototype

int NUMERIC

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

Click Source Link

Document

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

Usage

From source file:org.apache.syncope.core.util.ImportExport.java

private void setParameters(final String tableName, final Attributes attrs, final Query query) {

    Map<String, Integer> colTypes = new HashMap<String, Integer>();

    final Table table = getTable(tableName);

    for (int i = 0; i < attrs.getLength(); i++) {
        Integer colType = table.getColumn(QualifiedDBIdentifier.newColumn(attrs.getQName(i))).getType();
        if (colType == null) {
            LOG.warn("No column type found for {}", attrs.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }/* w ww.j a va2s  . c o m*/

        switch (colType) {
        case Types.INTEGER:
        case Types.TINYINT:
        case Types.SMALLINT:
            try {
                query.setParameter(i + 1, Integer.valueOf(attrs.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Integer '{}'", attrs.getValue(i));
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.NUMERIC:
        case Types.DECIMAL:
        case Types.BIGINT:
            try {
                query.setParameter(i + 1, Long.valueOf(attrs.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Long '{}'", attrs.getValue(i));
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.DOUBLE:
            try {
                query.setParameter(i + 1, Double.valueOf(attrs.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Double '{}'", attrs.getValue(i));
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.REAL:
        case Types.FLOAT:
            try {
                query.setParameter(i + 1, Float.valueOf(attrs.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Float '{}'", attrs.getValue(i));
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            try {
                query.setParameter(i + 1,
                        DateUtils.parseDate(attrs.getValue(i), SyncopeConstants.DATE_PATTERNS),
                        TemporalType.TIMESTAMP);
            } catch (ParseException e) {
                LOG.error("Unparsable Date '{}'", attrs.getValue(i));
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            query.setParameter(i + 1, "1".equals(attrs.getValue(i)) ? Boolean.TRUE : Boolean.FALSE);
            break;

        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            try {
                query.setParameter(i + 1, Hex.decode(attrs.getValue(i)));
            } catch (IllegalArgumentException e) {
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.BLOB:
            try {
                query.setParameter(i + 1, Hex.decode(attrs.getValue(i)));
            } catch (IllegalArgumentException e) {
                LOG.warn("Error decoding hex string to specify a blob parameter", e);
                query.setParameter(i + 1, attrs.getValue(i));
            } catch (Exception e) {
                LOG.warn("Error creating a new blob parameter", e);
            }
            break;

        default:
            query.setParameter(i + 1, attrs.getValue(i));
        }
    }
}

From source file:org.springframework.jdbc.object.SqlUpdateTests.java

private void doTestNamedParameterUpdate(final boolean namedDeclarations) throws SQLException {
    mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
    mockPreparedStatement.setObject(2, new Integer(1), Types.DECIMAL);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeUpdate();
    ctrlPreparedStatement.setReturnValue(1);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }//from   w w  w .  ja v  a 2s  .c om
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    mockConnection.prepareStatement(UPDATE_INT_INT);
    ctrlConnection.setReturnValue(mockPreparedStatement);

    replay();

    class NamedParameterUpdater extends SqlUpdate {

        public NamedParameterUpdater() {
            setSql(UPDATE_NAMED_PARAMETERS);
            setDataSource(mockDataSource);
            if (namedDeclarations) {
                declareParameter(new SqlParameter("priceId", Types.DECIMAL));
                declareParameter(new SqlParameter("perfId", Types.NUMERIC));
            } else {
                declareParameter(new SqlParameter(Types.NUMERIC));
                declareParameter(new SqlParameter(Types.DECIMAL));
            }
            compile();
        }

        public int run(int performanceId, int type) {
            Map params = new HashMap();
            params.put("perfId", new Integer(performanceId));
            params.put("priceId", new Integer(type));
            return updateByNamedParam(params);
        }
    }

    NamedParameterUpdater pc = new NamedParameterUpdater();
    int rowsAffected = pc.run(1, 1);
    assertEquals(1, rowsAffected);
}

From source file:architecture.ee.web.community.profile.dao.jdbc.JdbcProfileDao.java

public InputStream getInputStream(ProfileImage image) {
    return getExtendedJdbcTemplate().queryForObject(
            getBoundSql("ARCHITECTURE_COMMUNITY.SELECT_PROFILE_IMAGE_DATA_BY_ID").getSql(),
            SqlQueryHelper.getInputStreamRowMapper(),
            new SqlParameterValue(Types.NUMERIC, image.getProfileImageId()));
}

From source file:architecture.ee.web.logo.dao.jdbc.JdbcLogoImageDao.java

protected void updateImageImputStream(LogoImage logoImage, InputStream inputStream) {
    getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_WEB.DELETE_LOGO_IMAGE_DATA_BY_ID").getSql(),
            new SqlParameterValue(Types.NUMERIC, logoImage.getLogoId()));
    if (getExtendedJdbcTemplate().getDatabaseType() == DatabaseType.oracle) {
        getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_WEB.INSERT_EMPTY_LOGO_IMAGE_DATA").getSql(),
                new SqlParameterValue(Types.NUMERIC, logoImage.getLogoId()));
        getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_WEB.UPDATE_LOGO_IMAGE_DATA").getSql(),
                new Object[] { new SqlLobValue(inputStream, logoImage.getImageSize(), getLobHandler()),
                        logoImage.getLogoId() },
                new int[] { Types.BLOB, Types.NUMERIC });
    } else {//w w w  .java  2s  .co  m
        getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_WEB.INSERT_LOGO_IMAGE_DATA").getSql(),
                new SqlParameterValue(Types.NUMERIC, logoImage.getLogoId()), new SqlParameterValue(Types.BLOB,
                        new SqlLobValue(inputStream, logoImage.getImageSize(), getLobHandler())));
    }
}

From source file:org.jumpmind.symmetric.service.impl.AbstractDataExtractorServiceTest.java

protected void save(TestExtract obj) {
    String updateSql = String.format(
            "update %s set varchar_value=?, longvarchar_value=?, timestamp_value=?, date_value=?, bit_value=?, bigint_value=?, decimal_value=? where id=?",
            TEST_TABLE);/*from  ww w  .ja  va 2 s  .c  om*/
    String insertSql = String.format(
            "insert into %s (varchar_value, longvarchar_value, timestamp_value, date_value, bit_value, bigint_value, decimal_value, id) values(?,?,?,?,?,?,?,?)",
            TEST_TABLE);

    if (0 == getSqlTemplate().update(updateSql,
            new Object[] { obj.getVarcharValue(), obj.getLongVarcharValue(), obj.getTimestampValue(),
                    obj.getDateValue(), obj.isBitValue(), obj.getBigIntValue(), obj.getDecimalValue(),
                    obj.getId() },
            new int[] { Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP, Types.DATE, Types.BIT, Types.NUMERIC,
                    Types.NUMERIC, Types.NUMERIC })) {
        getSqlTemplate().update(insertSql,
                new Object[] { obj.getVarcharValue(), obj.getLongVarcharValue(), obj.getTimestampValue(),
                        obj.getDateValue(), obj.isBitValue(), obj.getBigIntValue(), obj.getDecimalValue(),
                        obj.getId() },
                new int[] { Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP, Types.DATE, Types.BIT, Types.NUMERIC,
                        Types.NUMERIC, Types.NUMERIC });
    }

}

From source file:org.apache.openjpa.jdbc.schema.Schemas.java

/**
 * Return the java type for the given SQL type from {@link Types}.
 *///w  w  w.j ava  2 s  .c  o  m
public static Class<?> getJavaType(int type, int size, int decimals) {
    switch (type) {
    case Types.CHAR:
        if (size == 1)
            return char.class;
        // no break
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.CLOB:
        return String.class;
    case Types.BIT:
        return boolean.class;
    case Types.TINYINT:
        return byte.class;
    case Types.SMALLINT:
        return short.class;
    case Types.INTEGER:
        return int.class;
    case Types.BIGINT:
        return long.class;
    case Types.REAL:
    case Types.FLOAT:
        return float.class;
    case Types.DOUBLE:
    case Types.NUMERIC:
        return double.class;
    case Types.DECIMAL:
        // oracle uses this for everything, so look at size and decimals
        if (decimals == 0 && size < 10)
            return int.class;
        else if (decimals == 0)
            return long.class;
        return double.class;
    // ### return a BigDecimal if the size if out of double range?
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        return Date.class;
    default:
        return Object.class;
    }
}

From source file:org.apache.sqoop.manager.ConnManager.java

/**
 * Resolve a database-specific type to Avro data type.
 * @param sqlType     sql type/*from  w ww . j a  v  a2s. c  om*/
 * @return            avro type
 */
public Type toAvroType(int sqlType) {
    switch (sqlType) {
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
        return Type.INT;
    case Types.BIGINT:
        return Type.LONG;
    case Types.BIT:
    case Types.BOOLEAN:
        return Type.BOOLEAN;
    case Types.REAL:
        return Type.FLOAT;
    case Types.FLOAT:
    case Types.DOUBLE:
        return Type.DOUBLE;
    case Types.NUMERIC:
    case Types.DECIMAL:
        return Type.STRING;
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.LONGNVARCHAR:
    case Types.NVARCHAR:
    case Types.NCHAR:
        return Type.STRING;
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        return Type.STRING;
    case Types.BLOB:
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        return Type.BYTES;
    default:
        throw new IllegalArgumentException("Cannot convert SQL type " + sqlType);
    }
}

From source file:oscar.util.SqlUtils.java

/**
 * this utility-method assigns a particular value to a place holder of a PreparedStatement. it tries to find the correct setXxx() value, accoring to the field-type information
 * represented by "fieldType". quality: this method is bloody alpha (as you migth see :=)
 */// w  w w.j  a v a  2s  .  c o  m
public static void fillPreparedStatement(PreparedStatement ps, int col, Object val, int fieldType)
        throws SQLException {
    try {
        logger.info("fillPreparedStatement( ps, " + col + ", " + val + ", " + fieldType + ")...");
        Object value = null;
        // Check for hard-coded NULL
        if (!("$null$".equals(val))) {
            value = val;
        }
        if (value != null) {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setInt(col, Integer.parseInt((String) value));
                break;
            case FieldTypes.NUMERIC:
                ps.setBigDecimal(col, createAppropriateNumeric(value));
                break;
            case FieldTypes.CHAR:
                ps.setString(col, (String) value);
                break;
            case FieldTypes.DATE:
                ps.setDate(col, createAppropriateDate(value));
                break; // #checkme
            case FieldTypes.TIMESTAMP:
                ps.setTimestamp(col, java.sql.Timestamp.valueOf((String) value));
                break;
            case FieldTypes.DOUBLE:
                ps.setDouble(col, Double.valueOf((String) value).doubleValue());
                break;
            case FieldTypes.FLOAT:
                ps.setFloat(col, Float.valueOf((String) value).floatValue());
                break;
            case FieldTypes.LONG:
                ps.setLong(col, Long.parseLong(String.valueOf(value)));
                break;
            case FieldTypes.BLOB:
                FileHolder fileHolder = (FileHolder) value;
                try {
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(byteOut);
                    out.writeObject(fileHolder);
                    out.flush();
                    byte[] buf = byteOut.toByteArray();
                    byteOut.close();
                    out.close();
                    ByteArrayInputStream bytein = new ByteArrayInputStream(buf);
                    int byteLength = buf.length;
                    ps.setBinaryStream(col, bytein, byteLength);
                    // store fileHolder as a whole (this way we don't lose file meta-info!)
                } catch (IOException ioe) {
                    MiscUtils.getLogger().error("Error", ioe);
                    logger.info(ioe.toString());
                    throw new SQLException("error storing BLOB in database - " + ioe.toString(), null, 2);
                }
                break;
            case FieldTypes.DISKBLOB:
                ps.setString(col, (String) value);
                break;
            default:
                ps.setObject(col, value); // #checkme
            }
        } else {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setNull(col, java.sql.Types.INTEGER);
                break;
            case FieldTypes.NUMERIC:
                ps.setNull(col, java.sql.Types.NUMERIC);
                break;
            case FieldTypes.CHAR:
                ps.setNull(col, java.sql.Types.CHAR);
                break;
            case FieldTypes.DATE:
                ps.setNull(col, java.sql.Types.DATE);
                break;
            case FieldTypes.TIMESTAMP:
                ps.setNull(col, java.sql.Types.TIMESTAMP);
                break;
            case FieldTypes.DOUBLE:
                ps.setNull(col, java.sql.Types.DOUBLE);
                break;
            case FieldTypes.FLOAT:
                ps.setNull(col, java.sql.Types.FLOAT);
                break;
            case FieldTypes.BLOB:
                ps.setNull(col, java.sql.Types.BLOB);
            case FieldTypes.DISKBLOB:
                ps.setNull(col, java.sql.Types.CHAR);
            default:
                ps.setNull(col, java.sql.Types.OTHER);
            }
        }
    } catch (Exception e) {
        throw new SQLException("Field type seems to be incorrect - " + e.toString(), null, 1);
    }
}

From source file:architecture.ee.web.community.profile.dao.jdbc.JdbcProfileDao.java

protected void updateProfileImageImputStream(ProfileImage image, InputStream inputStream) {
    getExtendedJdbcTemplate().update(/* w  w w  . j a  va2s  .c o  m*/
            getBoundSql("ARCHITECTURE_COMMUNITY.DELETE_PROFILE_IMAGE_DATA_BY_ID").getSql(),
            new SqlParameterValue(Types.NUMERIC, image.getProfileImageId()));
    if (getExtendedJdbcTemplate().getDatabaseType() == DatabaseType.oracle) {
        getExtendedJdbcTemplate().update(
                getBoundSql("ARCHITECTURE_COMMUNITY.INSERT_EMPTY_PROFILE_IMAGE_DATA").getSql(),
                new SqlParameterValue(Types.NUMERIC, image.getProfileImageId()));
        getExtendedJdbcTemplate().update(
                getBoundSql("ARCHITECTURE_COMMUNITY.UPDATE_PROFILE_IMAGE_DATA").getSql(),
                new Object[] { new SqlLobValue(inputStream, image.getImageSize(), getLobHandler()),
                        image.getProfileImageId() },
                new int[] { Types.BLOB, Types.NUMERIC });
    } else {
        getExtendedJdbcTemplate().update(
                getBoundSql("ARCHITECTURE_COMMUNITY.INSERT_PROFILE_IMAGE_DATA").getSql(),
                new SqlParameterValue(Types.NUMERIC, image.getProfileImageId()), new SqlParameterValue(
                        Types.BLOB, new SqlLobValue(inputStream, image.getImageSize(), getLobHandler())));
    }
}

From source file:com.redhat.rhn.domain.config.ConfigurationFactory.java

/**
 * Save a new configuration file.//w  w w . ja v  a 2 s .c o  m
 * Note, this method uses a stored procedure, so it must be used for all newly
 * created configuration files.
 * NOTE: This configuration file must have a persisted configuration channel
 *       attached to it.  config channels also used stored procedures for
 *       insertions, so we can't simply ask hibernate to save it for us.
 * @param file The configuration file to persist
 * @return config file id
 */
public static Long saveNewConfigFile(ConfigFile file) {
    //This is designed to catch some of the cases in which the config channel
    //was not saved before the config file.
    //There is still the possibility that the config channel hasn't been committed to
    //the database yet, but someone has set its id.  This should never happen from the
    //web site, but it might happen from tests.
    if (file.getConfigChannel() == null || file.getConfigChannel().getId() == null) {
        throw new IllegalStateException("Config Channels must be " + "saved before config files");
    }

    //Have to commit the configFileName before we commit the
    // ConfigFile so the stored proc will have an ID to work with
    singleton.saveObject(file.getConfigFileName());

    CallableMode m = ModeFactory.getCallableMode("config_queries", "create_new_config_file");
    Map inParams = new HashMap();
    Map outParams = new HashMap();

    //this will generate a foreign-key constraint violation if the config
    //channel is not already persisted.
    inParams.put("config_channel_id_in", file.getConfigChannel().getId());
    inParams.put("name_in", file.getConfigFileName().getPath());
    // Outparam
    outParams.put("configFileId", new Integer(Types.NUMERIC));

    Map result = m.execute(inParams, outParams);
    return (Long) result.get("configFileId");
}