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:com.flexive.core.storage.GenericDivisionExporter.java

/**
 * Dump a generic table to XML//  w w  w  .j  av  a 2  s.c  o m
 *
 * @param tableName     name of the table
 * @param stmt          an open statement
 * @param out           output stream
 * @param sb            an available and valid StringBuilder
 * @param xmlTag        name of the xml tag to write per row
 * @param idColumn      (optional) id column to sort results
 * @param onlyBinaries  process binary fields (else these will be ignored)
 * @throws SQLException on errors
 * @throws IOException  on errors
 */
private void dumpTable(String tableName, Statement stmt, OutputStream out, StringBuilder sb, String xmlTag,
        String idColumn, boolean onlyBinaries) throws SQLException, IOException {
    ResultSet rs = stmt.executeQuery("SELECT * FROM " + tableName
            + (StringUtils.isEmpty(idColumn) ? "" : " ORDER BY " + idColumn + " ASC"));
    final ResultSetMetaData md = rs.getMetaData();
    String value, att;
    boolean hasSubTags;
    while (rs.next()) {
        hasSubTags = false;
        if (!onlyBinaries) {
            sb.setLength(0);
            sb.append("  <").append(xmlTag);
        }
        for (int i = 1; i <= md.getColumnCount(); i++) {
            value = null;
            att = md.getColumnName(i).toLowerCase();
            switch (md.getColumnType(i)) {
            case java.sql.Types.DECIMAL:
            case java.sql.Types.NUMERIC:
            case java.sql.Types.BIGINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getBigDecimal(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.INTEGER:
            case java.sql.Types.SMALLINT:
            case java.sql.Types.TINYINT:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getLong(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.DOUBLE:
            case java.sql.Types.FLOAT:
            case java.sql.Types.REAL:
                if (!onlyBinaries) {
                    value = String.valueOf(rs.getDouble(i));
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.TIMESTAMP:
            case java.sql.Types.DATE:
                if (!onlyBinaries) {
                    final Timestamp ts = rs.getTimestamp(i);
                    if (rs.wasNull())
                        value = null;
                    else
                        value = FxFormatUtils.getDateTimeFormat().format(ts);
                }
                break;
            case java.sql.Types.BIT:
            case java.sql.Types.CHAR:
            case java.sql.Types.BOOLEAN:
                if (!onlyBinaries) {
                    value = rs.getBoolean(i) ? "1" : "0";
                    if (rs.wasNull())
                        value = null;
                }
                break;
            case java.sql.Types.CLOB:
            case java.sql.Types.BLOB:
            case java.sql.Types.LONGVARBINARY:
            case java.sql.Types.LONGVARCHAR:
            case java.sql.Types.VARBINARY:
            case java.sql.Types.VARCHAR:
            case java.sql.Types.BINARY:
            case SQL_LONGNVARCHAR:
            case SQL_NCHAR:
            case SQL_NCLOB:
            case SQL_NVARCHAR:

                hasSubTags = true;
                break;
            default:
                LOG.warn("Unhandled type [" + md.getColumnType(i) + "] for [" + tableName + "." + att + "]");
            }
            if (value != null && !onlyBinaries)
                sb.append(' ').append(att).append("=\"").append(value).append("\"");
        }
        if (hasSubTags) {
            if (!onlyBinaries)
                sb.append(">\n");
            for (int i = 1; i <= md.getColumnCount(); i++) {
                switch (md.getColumnType(i)) {
                case java.sql.Types.VARBINARY:
                case java.sql.Types.LONGVARBINARY:
                case java.sql.Types.BLOB:
                case java.sql.Types.BINARY:
                    if (idColumn == null)
                        throw new IllegalArgumentException("Id column required to process binaries!");
                    String binFile = FOLDER_BINARY + "/BIN_" + String.valueOf(rs.getLong(idColumn)) + "_" + i
                            + ".blob";
                    att = md.getColumnName(i).toLowerCase();
                    if (onlyBinaries) {
                        if (!(out instanceof ZipOutputStream))
                            throw new IllegalArgumentException(
                                    "out has to be a ZipOutputStream to store binaries!");
                        ZipOutputStream zip = (ZipOutputStream) out;
                        InputStream in = rs.getBinaryStream(i);
                        if (rs.wasNull())
                            break;

                        ZipEntry ze = new ZipEntry(binFile);
                        zip.putNextEntry(ze);

                        byte[] buffer = new byte[4096];
                        int read;
                        while ((read = in.read(buffer)) != -1)
                            zip.write(buffer, 0, read);
                        in.close();
                        zip.closeEntry();
                        zip.flush();
                    } else {
                        InputStream in = rs.getBinaryStream(i); //need to fetch to see if it is empty
                        if (rs.wasNull())
                            break;
                        in.close();
                        sb.append("    <").append(att).append(">").append(binFile).append("</").append(att)
                                .append(">\n");
                    }
                    break;
                case java.sql.Types.CLOB:
                case SQL_LONGNVARCHAR:
                case SQL_NCHAR:
                case SQL_NCLOB:
                case SQL_NVARCHAR:
                case java.sql.Types.LONGVARCHAR:
                case java.sql.Types.VARCHAR:
                    if (!onlyBinaries) {
                        value = rs.getString(i);
                        if (rs.wasNull())
                            break;
                        att = md.getColumnName(i).toLowerCase();
                        sb.append("    <").append(att).append('>');
                        escape(sb, value);
                        sb.append("</").append(att).append(">\n");
                    }
                    break;
                }
            }
            if (!onlyBinaries)
                sb.append("  </").append(xmlTag).append(">\n");
        } else {
            if (!onlyBinaries)
                sb.append("/>\n");
        }
        if (!onlyBinaries)
            write(out, sb);
    }
}

From source file:org.castor.jdo.engine.SQLTypeInfos.java

/**
 * Get value from given ResultSet at given index with given SQL type.
 * /*ww w.j  a v  a  2  s. com*/
 * @param rs The ResultSet to get the value from.
 * @param index The index of the value in the ResultSet.
 * @param sqlType The SQL type of the value.
 * @return The value.
 * @throws SQLException If a database access error occurs.
 */
public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException {
    switch (sqlType) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
        return rs.getString(index);
    case Types.DECIMAL:
    case Types.NUMERIC:
        return rs.getBigDecimal(index);
    case Types.INTEGER:
        int intVal = rs.getInt(index);
        return (rs.wasNull() ? null : new Integer(intVal));
    case Types.TIME:
        return rs.getTime(index, getCalendar());
    case Types.DATE:
        return rs.getDate(index);
    case Types.TIMESTAMP:
        return rs.getTimestamp(index, getCalendar());
    case Types.FLOAT:
    case Types.DOUBLE:
        double doubleVal = rs.getDouble(index);
        return (rs.wasNull() ? null : new Double(doubleVal));
    case Types.REAL:
        float floatVal = rs.getFloat(index);
        return (rs.wasNull() ? null : new Float(floatVal));
    case Types.SMALLINT:
        short shortVal = rs.getShort(index);
        return (rs.wasNull() ? null : new Short(shortVal));
    case Types.TINYINT:
        byte byteVal = rs.getByte(index);
        return (rs.wasNull() ? null : new Byte(byteVal));
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
    case Types.BINARY:
        return rs.getBytes(index);
    case Types.BLOB:
        Blob blob = rs.getBlob(index);
        return (blob == null ? null : blob.getBinaryStream());
    case Types.CLOB:
        return rs.getClob(index);
    case Types.BIGINT:
        long longVal = rs.getLong(index);
        return (rs.wasNull() ? null : new Long(longVal));
    case Types.BIT:
        boolean boolVal = rs.getBoolean(index);
        return (rs.wasNull() ? null : new Boolean(boolVal));
    default:
        Object value = rs.getObject(index);
        return (rs.wasNull() ? null : value);
    }
}

From source file:com.flexive.ejb.beans.workflow.StepDefinitionEngineBean.java

/**
 * {@inheritDoc}/*from  w  w w  .  j  ava  2  s. co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(StepDefinition stepDefinition) throws FxApplicationException {

    final UserTicket ticket = FxContext.getUserTicket();
    // Security checks
    FxPermissionUtils.checkRole(ticket, Role.WorkflowManagement);
    // Create the new step
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    FxString label = stepDefinition.getLabel();
    if (StringUtils.isEmpty(stepDefinition.getName()))
        throw new FxInvalidParameterException("NAME", "ex.stepdefinition.name.empty");
    if (label.isEmpty())
        throw new FxInvalidParameterException("LABEL", "ex.stepdefinition.label.empty");
    String name = stepDefinition.getName();
    long uniqueTargetId = stepDefinition.getUniqueTargetId();
    boolean success = false;
    long newId = -1;
    try {
        // Check the unique target
        checkValidUniqueTarget(-1, uniqueTargetId);

        if (StringUtils.isBlank(label.getDefaultTranslation())) {
            FxInvalidParameterException ip = new FxInvalidParameterException("NAME",
                    "ex.stepdefinition.name.empty");
            if (LOG.isDebugEnabled())
                LOG.debug(ip);
            throw ip;
        }

        // Obtain a database connection
        con = Database.getDbConnection();

        // Create the new workflow instance
        sql = "INSERT INTO " + TBL_WORKFLOW_STEPDEFINITION + " (ID,NAME,UNIQUE_TARGET) VALUES (?,?,?)";
        ps = con.prepareStatement(sql);
        newId = seq.getId(FxSystemSequencer.STEPDEFINITION);
        ps.setLong(1, newId);
        ps.setString(2, name);
        if (uniqueTargetId != -1) {
            ps.setLong(3, uniqueTargetId);
        } else {
            ps.setNull(3, Types.NUMERIC);
        }
        if (ps.executeUpdate() != 1)
            throw new FxCreateException(LOG, "ex.stepdefinition.create");
        Database.storeFxString(label, con, TBL_WORKFLOW_STEPDEFINITION, "name", "id", newId);
        success = true;
    } catch (FxInvalidParameterException exc) {
        throw exc;
    } catch (Exception exc) {
        if (StorageManager.isUniqueConstraintViolation(exc)) {
            FxEntryExistsException ee = new FxEntryExistsException("ex.stepdefinition.name.exists", name);
            if (LOG.isDebugEnabled())
                LOG.debug(ee);
            throw ee;
        } else {
            FxCreateException ce = new FxCreateException(LOG, "ex.stepdefinition.create", exc);
            LOG.error("Internal error: " + exc.getMessage(), ce);
            throw ce;
        }
    } finally {
        Database.closeObjects(StepDefinitionEngineBean.class, con, ps);
        if (!success) {
            EJBUtils.rollback(ctx);
        } else {
            StructureLoader.reloadWorkflows(FxContext.get().getDivisionId());
        }
    }
    return newId;
}

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

public void testUpdateMixed() throws SQLException {
    mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
    mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC, 2);
    mockPreparedStatement.setString(3, "rod");
    mockPreparedStatement.setObject(4, Boolean.TRUE, Types.BOOLEAN);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeUpdate();
    ctrlPreparedStatement.setReturnValue(1);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }/*from  w w  w .j  a  va2  s .c o m*/
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

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

    replay();

    MixedUpdater pc = new MixedUpdater();
    int rowsAffected = pc.run(1, 1, "rod", true);
    assertEquals(1, rowsAffected);
}

From source file:com.redhat.rhn.common.db.datasource.test.AdvDataSourceTest.java

public void testStoredProcedureJDBC() throws Exception {
    CallableMode m = ModeFactory.getCallableMode("test_queries", "stored_procedure_jdbc_format");
    Map inParams = new HashMap();
    Map outParams = new HashMap();
    inParams.put("label", "noarch");
    outParams.put("arch", new Integer(Types.NUMERIC));
    Map row = m.execute(inParams, outParams);
    assertNotNull(row);//from w  ww .  jav  a2s  .co m
    assertEquals(100, ((Long) row.get("arch")).intValue());

}

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

public LogoImage getLogoImageById(long logoId) throws LogoImageNotFoundException {
    try {/*from   w  w  w  .  j a va 2s  .  c o  m*/
        return getExtendedJdbcTemplate().queryForObject(
                getBoundSql("ARCHITECTURE_WEB.SELECT_LOGO_IMAGE_BY_ID").getSql(), logoMapper,
                new SqlParameterValue(Types.NUMERIC, logoId));
    } catch (DataAccessException e) {
        e.printStackTrace();
        throw new LogoImageNotFoundException(e);
    }
}

From source file:madgik.exareme.master.queryProcessor.analyzer.stat.ExternalStat.java

private int computeColumnSize(String columnName, int columnType, String table_sample) throws Exception {
    int columnSize = 0;
    if (columnType == Types.INTEGER || columnType == Types.REAL || columnType == Types.DOUBLE
            || columnType == Types.DECIMAL || columnType == Types.FLOAT || columnType == Types.NUMERIC) {
        columnSize = NUM_SIZE;//from   ww w.jav  a2  s .c  om
    } else if (columnType == Types.VARCHAR) {
        String query0 = "select max(length(" + columnName + ")) as length from (select " + columnName + " from "
                + table_sample + ") A" + " where " + columnName + " is not null limit " + MAX_STRING_SAMPLE;

        if (con.getClass().getName().contains("oracle")) {
            query0 = "select max(length(" + columnName + ")) as length from (select " + columnName + " from "
                    + table_sample + ") A" + " where " + columnName + " is not null and ROWNUM< "
                    + MAX_STRING_SAMPLE;
        }
        log.debug("executing col size query:" + query0);
        Statement stmt0 = con.createStatement();
        ResultSet rs0 = stmt0.executeQuery(query0);

        while (rs0.next()) {
            columnSize = rs0.getInt("length");
        }
        rs0.close();
        stmt0.close();

    } else if (columnType == Types.BLOB)
        columnSize = BLOB_SIZE;

    return columnSize;
}

From source file:org.jumpmind.db.platform.interbase.InterbaseDdlReader.java

protected void adjustColumns(Table table) {
    Column[] columns = table.getColumns();

    for (int idx = 0; idx < columns.length; idx++) {
        if (columns[idx].getMappedTypeCode() == Types.FLOAT) {
            columns[idx].setMappedTypeCode(Types.REAL);
        } else if ((columns[idx].getMappedTypeCode() == Types.NUMERIC)
                || (columns[idx].getMappedTypeCode() == Types.DECIMAL)) {
            if ((columns[idx].getMappedTypeCode() == Types.NUMERIC) && (columns[idx].getSizeAsInt() == 18)
                    && (columns[idx].getScale() == 0)) {
                columns[idx].setMappedTypeCode(Types.BIGINT);
            }//from   w  w w . j  av a  2 s.  c o  m
        } else if (TypeMap.isTextType(columns[idx].getMappedTypeCode())) {
            columns[idx].setDefaultValue(unescape(columns[idx].getDefaultValue(), "'", "''"));
        }
    }
}

From source file:architecture.user.dao.impl.ExternalJdbcUserDao.java

/**
 *  ? ?./*  w  w  w . j a  v  a  2 s . c  o  m*/
 * 
 * @param u
 */
public User create(User u) {
    UserTemplate user = new UserTemplate(u);
    if (user.getEmail() == null)
        throw new IllegalArgumentException(
                "User has no email address specified.  An email address is required to create a new user.");

    long userId = getNextId(sequencerName);

    user.setUserId(userId);
    if ("".equals(user.getName()))
        user.setName(null);
    user.setEmail(user.getEmail().toLowerCase());
    if (user.getStatus() == null)
        user.setStatus(User.Status.registered);

    boolean useLastNameFirstName = user.getFirstName() != null && user.getLastName() != null;

    try {

        Date now = new Date();

        getExtendedJdbcTemplate().update(getSql("CREATE_USER"),
                new Object[] { userId, user.getUsername(), user.getPasswordHash(),
                        useLastNameFirstName ? null : user.getName(), user.isNameVisible() ? 1 : 0,
                        user.getEmail(), user.isEmailVisible() ? 1 : 0,
                        user.getLastLoggedIn() != null ? user.getLastLoggedIn() : now,

                        user.getLastProfileUpdate() != null ? user.getLastProfileUpdate() : now,
                        user.isEnabled() ? 1 : 0, 1, user.isExternal() ? 1 : 0, user.isFederated() ? 1 : 0,
                        user.getStatus().getId(), user.getCreationDate() != null ? user.getCreationDate() : now,
                        user.getModifiedDate() != null ? user.getModifiedDate() : now },
                new int[] { Types.NUMERIC, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.NUMERIC,
                        Types.VARCHAR, Types.NUMERIC, Types.DATE,

                        Types.DATE, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC, Types.NUMERIC,
                        Types.DATE, Types.DATE });

        setUserProfile(user.getUserId(), user.getProfile());
        setUserProperties(user.getUserId(), user.getProperties());

    } catch (DataAccessException e) {
        String message = "Failed to create new user.";
        log.fatal(message, e);
        throw e;
    }
    return user;
}

From source file:org.apache.cayenne.migration.MigrationGenerator.java

protected String nameForJdbcType(int type) {
    switch (type) {
    case Types.ARRAY:
        return "array";
    case Types.BIGINT:
        return "bigInt";
    case Types.BINARY:
        return "binary";
    case Types.BIT:
        return "bit";
    case Types.BLOB:
        return "blob";
    case Types.BOOLEAN:
        return "boolean";
    case Types.CHAR:
        return "char";
    case Types.CLOB:
        return "clob";
    case Types.DATE:
        return "date";
    case Types.DECIMAL:
        return "decimal";
    case Types.DOUBLE:
        return "double";
    case Types.FLOAT:
        return "float";
    case Types.INTEGER:
        return "integer";
    case Types.LONGVARBINARY:
        return "longVarBinary";
    case Types.LONGVARCHAR:
        return "longVarChar";
    case Types.NUMERIC:
        return "numeric";
    case Types.REAL:
        return "real";
    case Types.SMALLINT:
        return "smallInt";
    case Types.TIME:
        return "time";
    case Types.TIMESTAMP:
        return "timestamp";
    case Types.TINYINT:
        return "tinyInt";
    case Types.VARBINARY:
        return "varBinary";
    case Types.VARCHAR:
        return "varchar";
    default:/*from  w  w  w  .ja  v  a 2  s .  c o m*/
        return null;
    }
}