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.google.visualization.datasource.util.SqlDataSourceHelper.java

/**
 * Converts the given SQL type to a value type.
 *
 * @param sqlType The sql type to be converted.
 *
 * @return The value type that fits the given sql type.
 *///  w  w  w. j  av  a 2 s  . c o m
private static ValueType sqlTypeToValueType(int sqlType) {
    ValueType valueType;
    switch (sqlType) {
    case Types.BOOLEAN:
    case Types.BIT: {
        valueType = ValueType.BOOLEAN;
        break;
    }
    case Types.CHAR:
    case Types.VARCHAR:
        valueType = ValueType.TEXT;
        break;
    case Types.INTEGER:
    case Types.SMALLINT:
    case Types.BIGINT:
    case Types.TINYINT:
    case Types.REAL:
    case Types.NUMERIC:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.DECIMAL:
        valueType = ValueType.NUMBER;
        break;
    case Types.DATE:
        valueType = ValueType.DATE;
        break;
    case Types.TIME:
        valueType = ValueType.TIMEOFDAY;
        break;
    case Types.TIMESTAMP:
        valueType = ValueType.DATETIME;
        break;
    default:
        valueType = ValueType.TEXT;
        break;
    }
    return valueType;
}

From source file:org.springframework.jdbc.core.simple.SimpleJdbcTemplateTests.java

public void testBatchUpdateWithListOfObjectArraysPlusTypeInfo() throws Exception {

    final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?";
    final List<Object[]> ids = new ArrayList<Object[]>();
    ids.add(new Object[] { 100 });
    ids.add(new Object[] { 200 });
    final int[] sqlTypes = new int[] { Types.NUMERIC };
    final int[] rowsAffected = new int[] { 1, 2 };

    MockControl ctrlDataSource = MockControl.createControl(DataSource.class);
    DataSource mockDataSource = (DataSource) ctrlDataSource.getMock();
    MockControl ctrlConnection = MockControl.createControl(Connection.class);
    Connection mockConnection = (Connection) ctrlConnection.getMock();
    MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock();
    MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class);
    DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock();

    BatchUpdateTestHelper.prepareBatchUpdateMocks(sql, ids, sqlTypes, rowsAffected, ctrlDataSource,
            mockDataSource, ctrlConnection, mockConnection, ctrlPreparedStatement, mockPreparedStatement,
            ctrlDatabaseMetaData, mockDatabaseMetaData);

    BatchUpdateTestHelper.replayBatchUpdateMocks(ctrlDataSource, ctrlConnection, ctrlPreparedStatement,
            ctrlDatabaseMetaData);/*from  ww w  .j  av a2s  .  co  m*/

    JdbcTemplate template = new JdbcTemplate(mockDataSource, false);
    SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(template);

    int[] actualRowsAffected = simpleJdbcTemplate.batchUpdate(sql, ids, sqlTypes);

    assertTrue("executed 2 updates", actualRowsAffected.length == 2);
    assertEquals(rowsAffected[0], actualRowsAffected[0]);
    assertEquals(rowsAffected[1], actualRowsAffected[1]);

    BatchUpdateTestHelper.verifyBatchUpdateMocks(ctrlPreparedStatement, ctrlDatabaseMetaData);
}

From source file:CSVWriter.java

private String getColumnValue(ResultSet rs, int colType, int colIndex) throws SQLException, IOException {

    String value = "";

    switch (colType) {
    case Types.BIT:
    case Types.JAVA_OBJECT:
        value = handleObject(rs.getObject(colIndex));
        break;/*from   ww w  . j a v  a 2s. com*/
    case Types.BOOLEAN:
        boolean b = rs.getBoolean(colIndex);
        value = Boolean.valueOf(b).toString();
        break;
    case NCLOB: // todo : use rs.getNClob
    case Types.CLOB:
        Clob c = rs.getClob(colIndex);
        if (c != null) {
            value = read(c);
        }
        break;
    case Types.BIGINT:
        value = handleLong(rs, colIndex);
        break;
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.REAL:
    case Types.NUMERIC:
        value = handleBigDecimal(rs.getBigDecimal(colIndex));
        break;
    case Types.INTEGER:
    case Types.TINYINT:
    case Types.SMALLINT:
        value = handleInteger(rs, colIndex);
        break;
    case Types.DATE:
        value = handleDate(rs, colIndex);
        break;
    case Types.TIME:
        value = handleTime(rs.getTime(colIndex));
        break;
    case Types.TIMESTAMP:
        value = handleTimestamp(rs.getTimestamp(colIndex));
        break;
    case NVARCHAR: // todo : use rs.getNString
    case NCHAR: // todo : use rs.getNString
    case LONGNVARCHAR: // todo : use rs.getNString
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.CHAR:
        value = rs.getString(colIndex);
        break;
    default:
        value = "";
    }

    if (value == null) {
        value = "";
    }

    return value;

}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

private void registerOutputParameters(CallableStatement cs, ParameterMapping[] mappings) throws SQLException {
    for (int i = 0; i < mappings.length; i++) {
        ParameterMapping mapping = ((ParameterMapping) mappings[i]);
        if (mapping.isOutputAllowed()) {
            if (null != mapping.getTypeName() && !mapping.getTypeName().equals("")) { // @added
                cs.registerOutParameter(i + 1, mapping.getJdbcType(), mapping.getTypeName());
            } else {
                if (mapping.getNumericScale() != null
                        && (mapping.getJdbcType() == Types.NUMERIC || mapping.getJdbcType() == Types.DECIMAL)) {
                    cs.registerOutParameter(i + 1, mapping.getJdbcType(), mapping.getNumericScale().intValue());
                } else {
                    cs.registerOutParameter(i + 1, mapping.getJdbcType());
                }//from   ww w .ja  va 2s .c  om
            }
        }
    }
}

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

/**
 * Using a stored procedure that looks up the config file name and will
 * create one if it does not exist.// w w  w  .  j a v  a  2  s  . com
 * @param path the path for the <code>ConfigFileName</code>
 * @return The id of the found config file name
 */
private static Long lookupConfigFileName(String path) {
    CallableMode m = ModeFactory.getCallableMode("config_queries", "lookup_config_filename");

    Map inParams = new HashMap();
    Map outParams = new HashMap();

    inParams.put("name_in", path);
    outParams.put("name_id", new Integer(Types.NUMERIC));

    Map out = m.execute(inParams, outParams);

    return (Long) out.get("name_id");
}

From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java

private int getSqlTypeFor(Object o) {
    if (o instanceof String) {
        return Types.VARCHAR;
    } else if (o instanceof Date) {
        return Types.DATE;
    } else if (o instanceof Integer) {
        return Types.INTEGER;
    } else if (o instanceof Double) {
        return Types.DOUBLE;
    } else if (o instanceof Float) {
        return Types.FLOAT;
    } else if (o instanceof BigInteger) {
        return Types.BIGINT;
    } else if (o instanceof BigDecimal) {
        return Types.NUMERIC;
    } else {//from  w ww. j av  a 2 s . c om
        return Types.OTHER;
    }
}

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

public void testListCustomersIntInt() throws SQLException {
    mockResultSet.next();/*  w w w .j  ava  2 s  .  com*/
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(1);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("rod");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(2);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("dave");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeQuery();
    ctrlPreparedStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

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

    replay();

    class CustomerQuery extends MappingSqlQuery {

        public CustomerQuery(DataSource ds) {
            super(ds, SELECT_ID_WHERE);
            declareParameter(new SqlParameter(Types.NUMERIC));
            declareParameter(new SqlParameter(Types.NUMERIC));
            compile();
        }

        protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
            Customer cust = new Customer();
            cust.setId(rs.getInt(COLUMN_NAMES[0]));
            cust.setForename(rs.getString(COLUMN_NAMES[1]));
            return cust;
        }
    }

    CustomerQuery query = new CustomerQuery(mockDataSource);
    List list = query.execute(1, 1);
    assertTrue("2 results in list", list.size() == 2);
    for (Iterator itr = list.iterator(); itr.hasNext();) {
        Customer cust = (Customer) itr.next();
    }
}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java

protected long _reorganizeSpace(Connection con, SequencerEngine seq, FxTreeMode sourceMode, FxTreeMode destMode,
        long nodeId, boolean includeNodeId, BigInteger overrideSpacing, BigInteger overrideLeft,
        FxTreeNodeInfo insertParent, int insertPosition, BigInteger insertSpace, BigInteger insertBoundaries[],
        int depthDelta, Long destinationNode, boolean createMode, boolean createKeepIds,
        boolean disableSpaceOptimization) throws FxTreeException {
    long firstCreatedNodeId = -1;
    FxTreeNodeInfoSpreaded nodeInfo;//ww  w.  j  a v a  2 s  .  c  o m
    try {
        nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, sourceMode, nodeId);
    } catch (Exception e) {
        return -1;
    }

    if (!nodeInfo.isSpaceOptimizable() && !disableSpaceOptimization) {
        // The Root node and cant be optimize any more ... so all we can do is fail :-/
        // This should never really happen
        if (nodeId == ROOT_NODE) {
            return -1;
        }
        //System.out.println("### UP we go, depthDelta=" + depthDelta);
        return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                depthDelta, destinationNode, createMode, createKeepIds, false);
    }

    BigInteger spacing = nodeInfo.getDefaultSpacing();
    if (overrideSpacing != null && (overrideSpacing.compareTo(spacing) < 0 || overrideLeft != null)) {
        // override spacing unless it is greater OR overrideLeft is specified (in that case we
        // have to use the spacing for valid tree ranges)  
        spacing = overrideSpacing;
    } else {
        if (spacing.compareTo(GO_UP) < 0 && !createMode && !disableSpaceOptimization) {
            return _reorganizeSpace(con, seq, sourceMode, destMode, nodeInfo.getParentId(), includeNodeId,
                    overrideSpacing, overrideLeft, insertParent, insertPosition, insertSpace, insertBoundaries,
                    depthDelta, destinationNode, createMode, createKeepIds, false);
        }
    }

    if (insertBoundaries != null && insertPosition == -1) {
        insertPosition = 0; // insertPosition cannot be negative
    }

    Statement stmt = null;
    PreparedStatement ps = null;
    ResultSet rs;
    BigInteger left = overrideLeft == null ? nodeInfo.getLeft() : overrideLeft;
    BigInteger right = null;
    String includeNode = includeNodeId ? "=" : "";
    long counter = 0;
    long newId = -1;
    try {
        final long start = System.currentTimeMillis();
        String createProps = createMode ? ",PARENT,REF,NAME,TEMPLATE" : "";
        String sql = " SELECT ID," + StorageManager.getIfFunction( // compute total child count only when the node has children
                "CHILDCOUNT = 0", "0",
                "(SELECT COUNT(*) FROM " + getTable(sourceMode) + " WHERE LFT > NODE.LFT AND RGT < NODE.RGT)") +
        // 3           4             5   6
                ", CHILDCOUNT, LFT AS LFTORD,RGT,DEPTH" + createProps
                + " FROM (SELECT ID,CHILDCOUNT,LFT,RGT,DEPTH" + createProps + " FROM " + getTable(sourceMode)
                + " WHERE " + "LFT>" + includeNode + nodeInfo.getLeft() + " AND LFT<" + includeNode
                + nodeInfo.getRight() + ") NODE " + "ORDER BY LFTORD ASC";
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        if (createMode) {
            //                                                                 1  2      3     4     5   6        7   8
            ps = con.prepareStatement(
                    "INSERT INTO " + getTable(destMode) + " (ID,PARENT,DEPTH,DIRTY,REF,TEMPLATE,LFT,RGT," +
                    //9           10    11
                            "CHILDCOUNT,NAME,MODIFIED_AT) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?)");
        } else {
            ps = con.prepareStatement("UPDATE " + getTable(sourceMode) + " SET LFT=?,RGT=?,DEPTH=? WHERE ID=?");
        }
        long id;
        int total_childs;
        int direct_childs;
        BigInteger nextLeft;
        int lastDepth = nodeInfo.getDepth() + (includeNodeId ? 0 : 1);
        int depth;
        BigInteger _rgt;
        BigInteger _lft;
        Long ref = null;
        String data = null;
        String name = "";

        Stack<Long> currentParent = null;
        if (createMode) {
            currentParent = new Stack<Long>();
            currentParent.push(destinationNode);
        }

        //System.out.println("Spacing:"+SPACING);
        while (rs.next()) {
            //System.out.println("------------------");
            id = rs.getLong(1);
            total_childs = rs.getInt(2);
            direct_childs = rs.getInt(3);
            _lft = getNodeBounds(rs, 4);
            _rgt = getNodeBounds(rs, 5);
            depth = rs.getInt(6);
            if (createMode) {
                // Reading these properties is slow, only do it when needed
                ref = rs.getLong(8);
                if (rs.wasNull())
                    ref = null;
                name = rs.getString(9);
                data = rs.getString(10);
                if (rs.wasNull())
                    data = null;
            }
            left = left.add(spacing).add(BigInteger.ONE);

            // Handle depth differences
            if (lastDepth - depth > 0) {
                BigInteger depthDifference = spacing.add(BigInteger.ONE);
                left = left.add(depthDifference.multiply(BigInteger.valueOf(lastDepth - depth)));
            }
            if (createMode) {
                if (lastDepth < depth) {
                    currentParent.push(newId);
                } else if (lastDepth > depth) {
                    for (int p = 0; p < (lastDepth - depth); p++)
                        currentParent.pop();
                }
            }

            right = left.add(spacing).add(BigInteger.ONE);

            // add child space if needed
            if (total_childs > 0) {
                BigInteger childSpace = spacing.multiply(BigInteger.valueOf(total_childs * 2));
                childSpace = childSpace.add(BigInteger.valueOf((total_childs * 2) - 1));
                right = right.add(childSpace);
                nextLeft = left;
            } else {
                nextLeft = right;
            }

            if (insertBoundaries != null) {
                // insert gap at requested position
                // If we're past the gap, keep adding the insert space to left/right because the added
                // space is never "injected" into the loop, i.e. without adding it the left/right boundaries of
                // nodes after the gap would be too far to the left.
                if (_lft.compareTo(insertBoundaries[0]) > 0) {
                    left = left.add(insertSpace);
                }
                if (_rgt.compareTo(insertBoundaries[0]) > 0) {
                    right = right.add(insertSpace);
                }
            }

            // sanity checks
            if (left.compareTo(right) >= 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "left greater than right");
            }
            if (insertParent != null && right.compareTo((BigInteger) insertParent.getRight()) > 0) {
                throw new FxTreeException(LOG, "ex.tree.reorganize.failed", counter, left, right,
                        "wrote past parent node bounds");
            }

            // Update the node
            if (createMode) {
                newId = createKeepIds ? id : seq.getId(destMode.getSequencer());
                if (firstCreatedNodeId == -1)
                    firstCreatedNodeId = newId;

                // Create the main entry
                ps.setLong(1, newId);
                ps.setLong(2, currentParent.peek());
                ps.setLong(3, depth + depthDelta);
                ps.setBoolean(4, destMode != FxTreeMode.Live); //only flag non-live tree's dirty
                if (ref == null) {
                    ps.setNull(5, java.sql.Types.NUMERIC);
                } else {
                    ps.setLong(5, ref);
                }
                if (data == null) {
                    ps.setNull(6, java.sql.Types.VARCHAR);
                } else {
                    ps.setString(6, data);
                }
                //                    System.out.println("=> id:"+newId+" left:"+left+" right:"+right);
                setNodeBounds(ps, 7, left);
                setNodeBounds(ps, 8, right);
                ps.setInt(9, direct_childs);
                ps.setString(10, name);
                ps.setLong(11, System.currentTimeMillis());
                ps.addBatch();
            } else {
                setNodeBounds(ps, 1, left);
                setNodeBounds(ps, 2, right);
                ps.setInt(3, depth + depthDelta);
                ps.setLong(4, id);
                ps.addBatch();
                //                    ps.executeBatch();
                //                    ps.clearBatch();
            }

            // Prepare variables for the next node
            left = nextLeft;
            lastDepth = depth;
            counter++;

            // Execute batch every 10000 items to avoid out of memory
            if (counter % 10000 == 0) {
                ps.executeBatch();
                ps.clearBatch();
            }
        }
        rs.close();
        stmt.close();
        stmt = null;
        ps.executeBatch();

        if (LOG.isDebugEnabled()) {
            final long time = System.currentTimeMillis() - start;

            LOG.debug("Tree reorganization of " + counter + " items completed in " + time + " ms (spaceLen="
                    + spacing + ")");
        }
        return firstCreatedNodeId;
    } catch (FxApplicationException e) {
        throw e instanceof FxTreeException ? (FxTreeException) e : new FxTreeException(e);
    } catch (SQLException e) {
        String next = "";
        if (e.getNextException() != null)
            next = " next:" + e.getNextException().getMessage();
        if (StorageManager.isDuplicateKeyViolation(e))
            throw new FxTreeException(LOG, e, "ex.tree.reorganize.duplicateKey");
        throw new FxTreeException(LOG, e, "ex.tree.reorganize.failed", counter, left, right,
                e.getMessage() + next);
    } catch (Exception e) {
        throw new FxTreeException(e);
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Throwable t) {
            /*ignore*/}
        try {
            if (ps != null)
                ps.close();
        } catch (Throwable t) {
            /*ignore*/}
    }
}

From source file:org.siphon.jssql.SqlExecutor.java

private String translateTypeName(int columnType, String columnTypeName) {
    switch (columnType) {
    case Types.VARCHAR:
    case Types.CHAR:
    case Types.NCHAR:
    case Types.NVARCHAR:
    case Types.LONGVARCHAR:
    case Types.LONGNVARCHAR:
        return "STRING";

    case Types.INTEGER:
    case Types.SMALLINT:
        return "INT";
    case Types.BIGINT:
        return "LONG";
    case Types.FLOAT:
        return "FLOAT";
    case Types.REAL:
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.NUMERIC:
    case Types.DECIMAL:
        return "DECIMAL";

    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
    case Types.TIME_WITH_TIMEZONE:
        return "DATE";

    case Types.ROWID:
        return "ROWID";

    case Types.BLOB:
        return "BINARY"; // return "BLOB";

    case Types.CLOB:
        return "STRING"; // return "CLOB";

    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        return "BINARY";

    case Types.BOOLEAN:
        return "BOOLEAN";

    case Types.ARRAY:
        return "ARRAY";

    case Types.OTHER:
        return columnTypeName.toUpperCase();

    default:/*from www .  ja  v a  2 s.  c  om*/
        return "UNKNOWN";
    }
}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Get a String describing the supplied JDBC type constant.
 *
 * @param jdbcType The constant to be decoded.
 * @return The text decode of the type constant as a <code>String</code>.
 *//*from   w w w .  j av  a 2  s .  com*/
static String getJdbcTypeName(int jdbcType) {
    switch (jdbcType) {
    case java.sql.Types.ARRAY:
        return "ARRAY";
    case java.sql.Types.BIGINT:
        return "BIGINT";
    case java.sql.Types.BINARY:
        return "BINARY";
    case java.sql.Types.BIT:
        return "BIT";
    case java.sql.Types.BLOB:
        return "BLOB";
    case java.sql.Types.BOOLEAN:
        return "BOOLEAN";
    case java.sql.Types.CHAR:
        return "CHAR";
    case java.sql.Types.CLOB:
        return "CLOB";
    //            case JtdsStatement.DATALINK:       return "DATALINK";
    case java.sql.Types.DATE:
        return "DATE";
    case java.sql.Types.DECIMAL:
        return "DECIMAL";
    case java.sql.Types.DISTINCT:
        return "DISTINCT";
    case java.sql.Types.DOUBLE:
        return "DOUBLE";
    case java.sql.Types.FLOAT:
        return "FLOAT";
    case java.sql.Types.INTEGER:
        return "INTEGER";
    case java.sql.Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case java.sql.Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case java.sql.Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case java.sql.Types.NULL:
        return "NULL";
    case java.sql.Types.NUMERIC:
        return "NUMERIC";
    case java.sql.Types.OTHER:
        return "OTHER";
    case java.sql.Types.REAL:
        return "REAL";
    case java.sql.Types.REF:
        return "REF";
    case java.sql.Types.SMALLINT:
        return "SMALLINT";
    case java.sql.Types.STRUCT:
        return "STRUCT";
    case java.sql.Types.TIME:
        return "TIME";
    case java.sql.Types.TIMESTAMP:
        return "TIMESTAMP";
    case java.sql.Types.TINYINT:
        return "TINYINT";
    case java.sql.Types.VARBINARY:
        return "VARBINARY";
    case java.sql.Types.VARCHAR:
        return "VARCHAR";
    default:
        return "ERROR";
    }
}