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.ejb.beans.BriefcaseEngineBean.java

/**
 * {@inheritDoc}/*from  www .  j a v  a2 s  .  co  m*/
 */
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public long create(String name, String description, Long aclId, LifeCycleInfo forcedLifeCycleInfo)
        throws FxApplicationException {
    final UserTicket ticket = FxContext.getUserTicket();

    if (description == null) {
        description = "";
    }
    if (name == null || name.trim().length() == 0) {
        throw new FxInvalidParameterException("ex.briefcase.nameMissing", "name");
    }
    if (aclId != null && aclId != -1) {
        ACL acl;
        try {
            acl = new ACLEngineBean().load(aclId);
        } catch (Throwable t) {
            throw new FxInvalidParameterException("ex.briefcase.invalidAcl", "acl");
        }
        if (!ticket.mayCreateACL(aclId, ticket.getUserId())) {
            throw new FxNoAccessException("ex.briefcase.noCreatePermission", acl.getLabel());
        }

    }
    if (forcedLifeCycleInfo != null && !ticket.isGlobalSupervisor()) {
        throw new FxNoAccessException("ex.briefcase.lciPermission");
    }
    Connection con = null;
    PreparedStatement ps = null;
    String sql;
    String sourceQuery = "";

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

        // Obtain a new id
        long newId = seq.getId(FxSystemSequencer.BRIEFCASE);

        sql = "INSERT INTO " + DatabaseConst.TBL_BRIEFCASE + "(" + //1,   2,  3        ,  4         , 5 ,    6        7         8              9      , 10     , 11
                "ID,NAME,DESCRIPTION,SOURCE_QUERY,ACL,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT,MANDATOR,ICON_ID)"
                + "VALUES (?,?,?,?,?,?,?,?,?,?,1)";
        final long NOW = System.currentTimeMillis();
        ps = con.prepareStatement(sql);
        ps.setLong(1, newId);
        ps.setString(2, name);
        ps.setString(3, description);
        ps.setString(4, sourceQuery);
        if (aclId != null && aclId != -1) {
            ps.setLong(5, aclId);
        } else {
            ps.setNull(5, java.sql.Types.NUMERIC);
        }
        if (forcedLifeCycleInfo != null) {
            ps.setLong(6, forcedLifeCycleInfo.getCreatorId());
            ps.setLong(7, forcedLifeCycleInfo.getCreationTime());
            ps.setLong(8, forcedLifeCycleInfo.getModificatorId());
            ps.setLong(9, forcedLifeCycleInfo.getModificationTime());
        } else {
            ps.setLong(6, ticket.getUserId());
            ps.setLong(7, NOW);
            ps.setLong(8, ticket.getUserId());
            ps.setLong(9, NOW);
        }
        ps.setLong(10, ticket.getMandatorId());
        ps.executeUpdate();
        return newId;
    } catch (SQLException exc) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc);
        if (ctx != null) {
            EJBUtils.rollback(ctx);
        } else {
            try {
                if (con != null)
                    con.rollback();
            } catch (SQLException e) {
                LOG.warn(e.getMessage(), e);
            }
        }
        if (uniqueConstraintViolation) {
            throw new FxEntryExistsException(LOG, "ex.briefcase.nameAlreadyExists", name);
        } else {
            throw new FxCreateException(LOG, exc, "ex.briefcase.createFailed");
        }
    } finally {
        closeObjects(BriefcaseEngineBean.class, con, ps);
    }
}

From source file:architecture.ee.web.community.timeline.dao.jdbc.JdbcTimelineDao.java

public void deleteTimeline(Timeline timeline) {
    getJdbcTemplate().update(getBoundSql("ARCHITECTURE_COMMUNITY.DELETE_TIMELINE_BY_ID").getSql(),
            new SqlParameterValue(Types.NUMERIC, timeline.getTimelineId()));
}

From source file:org.jfree.data.jdbc.JDBCPieDataset.java

/**
 *  ExecuteQuery will attempt execute the query passed to it against the
 *  existing database connection.  If no connection exists then no action
 *  is taken./*from   w w  w . j a va  2  s  .c o  m*/
 *  The results from the query are extracted and cached locally, thus
 *  applying an upper limit on how many rows can be retrieved successfully.
 *
 * @param  query  the query to be executed
 * @param  con  the connection the query is to be executed against
 *
 * @throws SQLException if there is a problem executing the query.
 */
public void executeQuery(Connection con, String query) throws SQLException {

    Statement statement = null;
    ResultSet resultSet = null;

    try {
        statement = con.createStatement();
        resultSet = statement.executeQuery(query);
        ResultSetMetaData metaData = resultSet.getMetaData();

        int columnCount = metaData.getColumnCount();
        if (columnCount != 2) {
            throw new SQLException("Invalid sql generated.  PieDataSet requires 2 columns only");
        }

        int columnType = metaData.getColumnType(2);
        double value = Double.NaN;
        while (resultSet.next()) {
            Comparable key = resultSet.getString(1);
            switch (columnType) {
            case Types.NUMERIC:
            case Types.REAL:
            case Types.INTEGER:
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.DECIMAL:
            case Types.BIGINT:
                value = resultSet.getDouble(2);
                setValue(key, value);
                break;

            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP:
                Timestamp date = resultSet.getTimestamp(2);
                value = date.getTime();
                setValue(key, value);
                break;

            default:
                System.err.println("JDBCPieDataset - unknown data type");
                break;
            }
        }

        fireDatasetChanged(new DatasetChangeInfo());
        //TODO: fill in real change info

    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                System.err.println("JDBCPieDataset: swallowing exception.");
            }
        }
    }
}

From source file:com.glaf.core.jdbc.QueryHelper.java

@SuppressWarnings("unchecked")
public List<ColumnDefinition> getColumns(Connection conn, String sql, Map<String, Object> paramMap) {
    if (!DBUtils.isLegalQuerySql(sql)) {
        throw new RuntimeException(" SQL statement illegal ");
    }/*from w w w .  j  av a 2  s .c o m*/
    List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>();
    PreparedStatement psmt = null;
    ResultSetMetaData rsmd = null;
    ResultSet rs = null;
    try {
        List<Object> values = null;
        if (paramMap != null) {
            SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, paramMap);
            sql = sqlExecutor.getSql();
            values = (List<Object>) sqlExecutor.getParameter();
        }

        logger.debug("sql:\n" + sql);
        logger.debug("values:" + values);

        psmt = conn.prepareStatement(sql);

        if (values != null && !values.isEmpty()) {
            JdbcUtils.fillStatement(psmt, values);
        }

        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            int sqlType = rsmd.getColumnType(i);
            ColumnDefinition column = new ColumnDefinition();
            column.setColumnLabel(rsmd.getColumnLabel(i));
            column.setColumnName(rsmd.getColumnName(i));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(i));
            column.setScale(rsmd.getScale(i));
            column.setName(StringTools.camelStyle(column.getColumnLabel().toLowerCase()));
            if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                column.setJavaType("Long");
            }
            if (!columns.contains(column)) {
                columns.add(column);
            }
            logger.debug(column.getColumnName() + " sqlType:" + sqlType + " precision:" + column.getPrecision()
                    + " scale:" + column.getScale());
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
    return columns;
}

From source file:com.squid.core.domain.operators.ExtendedType.java

@JsonIgnore
public boolean isInteger() {
    switch (this.dataType) {
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.SMALLINT:
    case Types.TINYINT:
        return true;
    case Types.NUMERIC:
    case Types.DECIMAL:
        return scale == 0;
    default://  w w w.  ja  v a2s  . co m
        return false;
    }
}

From source file:com.manydesigns.portofino.model.database.ConnectionProvider.java

protected void fixMissingTypeAliases(List<Type> types) {
    Type numericType = null;//from ww w  .  j a  v  a 2s. com
    Type decimalType = null;
    for (Type type : types) {
        if (type.getJdbcType() == Types.NUMERIC) {
            numericType = type;
        } else if (type.getJdbcType() == Types.DECIMAL) {
            decimalType = type;
        }
    }
    if (numericType == null && decimalType != null) {
        numericType = new Type("NUMERIC", Types.NUMERIC, decimalType.getMaximumPrecision(),
                decimalType.getLiteralPrefix(), decimalType.getLiteralSuffix(), decimalType.isNullable(),
                decimalType.isCaseSensitive(), decimalType.isSearchable(), decimalType.isAutoincrement(),
                decimalType.getMinimumScale(), decimalType.getMaximumScale(), decimalType.isPrecisionRequired(),
                decimalType.isScaleRequired());
        types.add(numericType);
        logger.info("Added NUMERIC type as an alias of DECIMAL");
    } else if (decimalType == null && numericType != null) {
        decimalType = new Type("DECIMAL", Types.DECIMAL, numericType.getMaximumPrecision(),
                numericType.getLiteralPrefix(), numericType.getLiteralSuffix(), numericType.isNullable(),
                numericType.isCaseSensitive(), numericType.isSearchable(), numericType.isAutoincrement(),
                numericType.getMinimumScale(), numericType.getMaximumScale(), numericType.isPrecisionRequired(),
                numericType.isScaleRequired());
        types.add(decimalType);
        logger.info("Added DECIMAL type as an alias of NUMERIC");
    }
}

From source file:org.apache.torque.generator.source.jdbc.JdbcMetadataSource.java

@Override
protected SourceElement createRootElement() throws SourceException {
    SourceElement rootElement = new SourceElement("database");
    {//  w ww. j  a  v  a  2 s .com
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new SourceException("Could not find database driver class " + driver, e);
        }
        log.debug("DB driver " + driver + " loaded");
    }

    Connection con = null;
    try {

        con = DriverManager.getConnection(url, username, password);
        log.debug("DB connection to database " + url + " established");

        DatabaseMetaData dbMetaData = con.getMetaData();

        List<String> tableList = getTableNames(dbMetaData, schema);

        for (int i = 0; i < tableList.size(); i++) {
            // Add Table.
            String tableName = (String) tableList.get(i);
            log.debug("Processing table: " + tableName);

            SourceElement table = new SourceElement("table");
            rootElement.getChildren().add(table);
            table.setAttribute("name", tableName);

            List<ColumnMetadata> columns = getColumns(dbMetaData, tableName, schema);
            Set<String> primaryKeys = getPrimaryKeys(dbMetaData, tableName, schema);

            for (ColumnMetadata col : columns) {
                String name = col.getName();
                Integer type = col.getSqlType();
                int size = col.getSize().intValue();
                int scale = col.getDecimalDigits().intValue();

                Integer nullType = col.getNullType();
                String defValue = col.getDefValue();

                SourceElement column = new SourceElement("column");
                column.setAttribute("name", name);

                column.setAttribute("type", SchemaType.getByJdbcType(type).toString());

                if (size > 0 && (type.intValue() == Types.CHAR || type.intValue() == Types.VARCHAR
                        || type.intValue() == Types.LONGVARCHAR || type.intValue() == Types.DECIMAL
                        || type.intValue() == Types.NUMERIC)) {
                    column.setAttribute("size", String.valueOf(size));
                }

                if (scale > 0 && (type.intValue() == Types.DECIMAL || type.intValue() == Types.NUMERIC)) {
                    column.setAttribute("scale", String.valueOf(scale));
                }

                if (primaryKeys.contains(name)) {
                    column.setAttribute("primaryKey", "true");
                } else if (nullType.intValue() == 0) {
                    column.setAttribute("required", "true");
                }

                if (StringUtils.isNotEmpty(defValue)) {
                    // trim out parens & quotes out of def value.
                    // makes sense for MSSQL. not sure about others.
                    if (defValue.startsWith("(") && defValue.endsWith(")")) {
                        defValue = defValue.substring(1, defValue.length() - 1);
                    }

                    if (defValue.startsWith("'") && defValue.endsWith("'")) {
                        defValue = defValue.substring(1, defValue.length() - 1);
                    }

                    column.setAttribute("default", defValue);
                }
                table.getChildren().add(column);
            }

            // Foreign keys for this table.
            Collection<ForeignKeyMetadata> forgnKeys = getForeignKeys(dbMetaData, tableName, schema);
            for (ForeignKeyMetadata foreignKeyMetadata : forgnKeys) {
                SourceElement fk = new SourceElement("foreign-key");
                fk.setAttribute("foreignTable", foreignKeyMetadata.getReferencedTable());
                for (int m = 0; m < foreignKeyMetadata.getLocalColumns().size(); m++) {
                    SourceElement ref = new SourceElement("reference");
                    ref.setAttribute("local", foreignKeyMetadata.getLocalColumns().get(m));
                    ref.setAttribute("foreign", foreignKeyMetadata.getForeignColumns().get(m));
                    fk.getChildren().add(ref);
                }
                table.getChildren().add(fk);
            }
        }
    } catch (SQLException e) {
        throw new SourceException("Could not retrieve JDBC Metadata from url " + url, e);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                log.warn("Could not close database connection", e);
            }
            con = null;
        }
    }
    return rootElement;
}

From source file:CreateNewTable.java

private static Vector getDataTypes(Connection con) throws SQLException {
    String structName = null, distinctName = null, javaName = null;

    // create a vector of class DataType initialized with
    // the SQL code, the SQL type name, and two null entries
    // for the local type name and the creation parameter(s)

    Vector dataTypes = new Vector();
    dataTypes.add(new DataType(java.sql.Types.BIT, "BIT"));
    dataTypes.add(new DataType(java.sql.Types.TINYINT, "TINYINT"));
    dataTypes.add(new DataType(java.sql.Types.SMALLINT, "SMALLINT"));
    dataTypes.add(new DataType(java.sql.Types.INTEGER, "INTEGER"));
    dataTypes.add(new DataType(java.sql.Types.BIGINT, "BIGINT"));
    dataTypes.add(new DataType(java.sql.Types.FLOAT, "FLOAT"));
    dataTypes.add(new DataType(java.sql.Types.REAL, "REAL"));
    dataTypes.add(new DataType(java.sql.Types.DOUBLE, "DOUBLE"));
    dataTypes.add(new DataType(java.sql.Types.NUMERIC, "NUMERIC"));
    dataTypes.add(new DataType(java.sql.Types.DECIMAL, "DECIMAL"));
    dataTypes.add(new DataType(java.sql.Types.CHAR, "CHAR"));
    dataTypes.add(new DataType(java.sql.Types.VARCHAR, "VARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARCHAR, "LONGVARCHAR"));
    dataTypes.add(new DataType(java.sql.Types.DATE, "DATE"));
    dataTypes.add(new DataType(java.sql.Types.TIME, "TIME"));
    dataTypes.add(new DataType(java.sql.Types.TIMESTAMP, "TIMESTAMP"));
    dataTypes.add(new DataType(java.sql.Types.BINARY, "BINARY"));
    dataTypes.add(new DataType(java.sql.Types.VARBINARY, "VARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.LONGVARBINARY, "LONGVARBINARY"));
    dataTypes.add(new DataType(java.sql.Types.NULL, "NULL"));
    dataTypes.add(new DataType(java.sql.Types.OTHER, "OTHER"));
    dataTypes.add(new DataType(java.sql.Types.BLOB, "BLOB"));
    dataTypes.add(new DataType(java.sql.Types.CLOB, "CLOB"));

    DatabaseMetaData dbmd = con.getMetaData();
    ResultSet rs = dbmd.getTypeInfo();
    while (rs.next()) {
        int codeNumber = rs.getInt("DATA_TYPE");
        String dbmsName = rs.getString("TYPE_NAME");
        String createParams = rs.getString("CREATE_PARAMS");

        if (codeNumber == Types.STRUCT && structName == null)
            structName = dbmsName;//  www  .  ja  va 2  s . c o  m
        else if (codeNumber == Types.DISTINCT && distinctName == null)
            distinctName = dbmsName;
        else if (codeNumber == Types.JAVA_OBJECT && javaName == null)
            javaName = dbmsName;
        else {
            for (int i = 0; i < dataTypes.size(); i++) {
                // find entry that matches the SQL code, 
                // and if local type and params are not already set,
                // set them
                DataType type = (DataType) dataTypes.get(i);
                if (type.getCode() == codeNumber) {
                    type.setLocalTypeAndParams(dbmsName, createParams);
                }
            }
        }
    }

    int[] types = { Types.STRUCT, Types.DISTINCT, Types.JAVA_OBJECT };
    rs = dbmd.getUDTs(null, "%", "%", types);
    while (rs.next()) {
        String typeName = null;
        DataType dataType = null;

        if (dbmd.isCatalogAtStart())
            typeName = rs.getString(1) + dbmd.getCatalogSeparator() + rs.getString(2) + "." + rs.getString(3);
        else
            typeName = rs.getString(2) + "." + rs.getString(3) + dbmd.getCatalogSeparator() + rs.getString(1);

        switch (rs.getInt(5)) {
        case Types.STRUCT:
            dataType = new DataType(Types.STRUCT, typeName);
            dataType.setLocalTypeAndParams(structName, null);
            break;
        case Types.DISTINCT:
            dataType = new DataType(Types.DISTINCT, typeName);
            dataType.setLocalTypeAndParams(distinctName, null);
            break;
        case Types.JAVA_OBJECT:
            dataType = new DataType(Types.JAVA_OBJECT, typeName);
            dataType.setLocalTypeAndParams(javaName, null);
            break;
        }
        dataTypes.add(dataType);
    }

    return dataTypes;
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Get the Statement column so that the results are mapped correctly.
 * (this has been copied from AbstractDatabaseAction and modified slightly)
 *//*from  w w  w .j a  va 2  s.  c  o m*/
public static Object getColumn(ResultSet set, Configuration column) throws Exception {

    Integer type = (Integer) JDBCTypeConversions.typeConstants.get(column.getAttribute("type"));
    String dbcol = column.getAttribute("name");
    Object value = null;

    switch (type.intValue()) {
    case Types.CLOB:
    case Types.CHAR:
        Clob dbClob = set.getClob(dbcol);
        int length = (int) dbClob.length();
        InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream());
        byte[] buffer = new byte[length];
        asciiStream.read(buffer);
        String str = new String(buffer);
        asciiStream.close();
        value = str;
        break;
    case Types.BIGINT:
        value = set.getBigDecimal(dbcol);
        break;
    case Types.TINYINT:
        value = new Byte(set.getByte(dbcol));
        break;
    case Types.VARCHAR:
        value = set.getString(dbcol);
        break;
    case Types.DATE:
        value = set.getDate(dbcol);
        break;
    case Types.DOUBLE:
        value = new Double(set.getDouble(dbcol));
        break;
    case Types.FLOAT:
        value = new Float(set.getFloat(dbcol));
        break;
    case Types.INTEGER:
        value = new Integer(set.getInt(dbcol));
        break;
    case Types.NUMERIC:
        value = new Long(set.getLong(dbcol));
        break;
    case Types.SMALLINT:
        value = new Short(set.getShort(dbcol));
        break;
    case Types.TIME:
        value = set.getTime(dbcol);
        break;
    case Types.TIMESTAMP:
        value = set.getTimestamp(dbcol);
        break;
    case Types.ARRAY:
        value = set.getArray(dbcol); // new Integer(set.getInt(dbcol));
        break;
    case Types.BIT:
        value = BooleanUtils.toBooleanObject(set.getBoolean(dbcol));
        break;
    case Types.STRUCT:
        value = (Struct) set.getObject(dbcol);
        break;
    case Types.OTHER:
        value = set.getObject(dbcol);
        break;

    default:
        // The blob types have to be requested separately, via a Reader.
        value = "";
        break;
    }

    return value;
}

From source file:org.dashbuilder.dataprovider.backend.sql.JDBCUtils.java

public static ColumnType calculateType(int sqlDataType) {
    switch (sqlDataType) {

    // Category-like columns.
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.NCHAR:
    case Types.NVARCHAR:
    case Types.BIT:
    case Types.BOOLEAN: {
        return ColumnType.LABEL;
    }/*from  w  ww.  j  a  v  a 2s  .co m*/

    // Text-like columns.
    case Types.LONGVARCHAR:
    case Types.LONGNVARCHAR: {
        return ColumnType.TEXT;
    }

    // Number-like columns.
    case Types.TINYINT:
    case Types.BIGINT:
    case Types.INTEGER:
    case Types.DECIMAL:
    case Types.DOUBLE:
    case Types.FLOAT:
    case Types.NUMERIC:
    case Types.REAL:
    case Types.SMALLINT: {
        return ColumnType.NUMBER;
    }

    // Date-like columns.
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP: {
        return ColumnType.DATE;
    }

    /*case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
    case Types.NULL:
    case Types.OTHER:
    case Types.JAVA_OBJECT:
    case Types.DISTINCT:
    case Types.STRUCT:
    case Types.ARRAY:
    case Types.BLOB:
    case Types.CLOB:
    case Types.REF:
    case Types.ROWID:
    case Types.SQLXML:
    case Types.DATALINK:*/

    // Unsupported (see above) types are treated as a text values.
    default: {
        return ColumnType.TEXT;
    }
    }
}