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:at.bestsolution.persistence.java.Util.java

public static void setValue(PreparedStatement pstmt, int parameterIndex, TypedValue value) throws SQLException {
    if (value.value == null) {
        int sqlType;
        switch (value.type) {
        case INT:
            sqlType = Types.INTEGER;
            break;
        case DOUBLE:
            sqlType = Types.DECIMAL;
            break;
        case FLOAT:
            sqlType = Types.FLOAT;
            break;
        case BOOLEAN:
            sqlType = Types.BOOLEAN;
            break;
        case LONG:
            sqlType = Types.BIGINT;
            break;
        case STRING:
            sqlType = Types.VARCHAR;
            break;
        case BLOB:
            sqlType = Types.BLOB;
            break;
        case CLOB:
            sqlType = Types.CLOB;
            break;
        case TIMESTAMP:
            sqlType = Types.TIMESTAMP;
            break;
        default:/*from w ww.  j a v  a 2 s .  c  o m*/
            sqlType = Types.OTHER;
            break;
        }
        pstmt.setNull(parameterIndex, sqlType);
    } else {
        switch (value.type) {
        case INT:
            pstmt.setInt(parameterIndex, ((Number) value.value).intValue());
            break;
        case DOUBLE:
            pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue());
            break;
        case FLOAT:
            pstmt.setDouble(parameterIndex, ((Number) value.value).doubleValue());
            break;
        case BOOLEAN:
            pstmt.setBoolean(parameterIndex, Boolean.TRUE.equals(value.value));
            break;
        case LONG:
            pstmt.setLong(parameterIndex, ((Number) value.value).longValue());
            break;
        case STRING:
            pstmt.setString(parameterIndex, (String) value.value);
            break;
        case TIMESTAMP:
            if (value.value instanceof Timestamp) {
                pstmt.setTimestamp(parameterIndex, (Timestamp) value.value);
            } else {
                pstmt.setTimestamp(parameterIndex, new Timestamp(((Date) value.value).getTime()));
            }
            break;
        case UNKNOWN:
            pstmt.setObject(parameterIndex, value.value);
            break;
        default:
            throw new IllegalStateException("Unknown type");
        }
    }
}

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.// w  w  w.j a va  2 s. c  om
 *  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:org.apache.torque.generator.source.jdbc.JdbcMetadataSource.java

@Override
protected SourceElement createRootElement() throws SourceException {
    SourceElement rootElement = new SourceElement("database");
    {//from  www. j a v a2 s.  co m
        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: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.  j  a v  a  2s .c  o m*/
        return false;
    }
}

From source file:org.jumpmind.db.sql.DmlStatement.java

protected int getTypeCode(Column column, boolean isDateOverrideToTimestamp) {
    int type = column.getMappedTypeCode();
    if (type == Types.DATE && isDateOverrideToTimestamp) {
        type = Types.TIMESTAMP;//from  ww w . j  a  va2 s.com
    } else if (type == Types.FLOAT || type == Types.DOUBLE || type == Types.REAL) {
        type = Types.DECIMAL;
    }
    return type;
}

From source file:net.riezebos.thoth.configuration.persistence.dbs.DDLExecuter.java

private void initDialect(DatabaseIdiom idiom) {
    databaseIdiom = idiom;/*from  w  w  w .  java 2s . c om*/
    try {
        addTranslation("bigint", idiom.getTypeName(Types.BIGINT));
        addTranslation("binary", idiom.getTypeName(Types.BINARY));
        addTranslation("bit", idiom.getTypeName(Types.BIT));
        addTranslation("blob", idiom.getTypeName(Types.BLOB));
        addTranslation("boolean", idiom.getTypeName(Types.BOOLEAN));
        addTranslation("char", idiom.getTypeName(Types.CHAR));
        addTranslation("clob", idiom.getTypeName(Types.CLOB));
        addTranslation("date", idiom.getTypeName(Types.DATE));
        addTranslation("decimal", idiom.getTypeName(Types.DECIMAL));
        addTranslation("double", idiom.getTypeName(Types.DOUBLE));
        addTranslation("float", idiom.getTypeName(Types.FLOAT));
        addTranslation("integer", idiom.getTypeName(Types.INTEGER));
        addTranslation("longnvarchar", idiom.getTypeName(Types.LONGNVARCHAR));
        addTranslation("longvarbinary", idiom.getTypeName(Types.LONGVARBINARY));
        addTranslation("longvarchar", idiom.getTypeName(Types.LONGVARCHAR));
        addTranslation("nchar", idiom.getTypeName(Types.NCHAR));
        addTranslation("nclob", idiom.getTypeName(Types.NCLOB));
        addTranslation("numeric", idiom.getTypeName(Types.NUMERIC));
        addTranslation("nvarchar", idiom.getTypeName(Types.NVARCHAR));
        addTranslation("real", idiom.getTypeName(Types.REAL));
        addTranslation("smallint", idiom.getTypeName(Types.SMALLINT));
        addTranslation("time", idiom.getTypeName(Types.TIME));
        addTranslation("timestamp", idiom.getTypeName(Types.TIMESTAMP));
        addTranslation("tinyint", idiom.getTypeName(Types.TINYINT));
        addTranslation("varbinary", idiom.getTypeName(Types.VARBINARY));

        databaseIdiom.initDialect(translations, workarounds);
        // Ignore autogenerated ID's
        addWorkaround("generated always as identity", "");
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

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

protected void fixMissingTypeAliases(List<Type> types) {
    Type numericType = null;/*from  www.  j a v a2  s . co  m*/
    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.cloudgraph.rdb.service.RDBDataConverter.java

private int convertToSqlType(Property property, Object value) {
    int result;/*from w w w  .  j  av  a  2  s .  c o m*/
    if (!property.getType().isDataType())
        throw new IllegalArgumentException("expected data type property, not " + property.toString());
    DataType dataType = DataType.valueOf(property.getType().getName());
    switch (dataType) {
    case String:
    case URI:
    case Month:
    case MonthDay:
    case Day:
    case Time:
    case Year:
    case YearMonth:
    case YearMonthDay:
    case Duration:
    case Strings:
        result = java.sql.Types.VARCHAR;
        break;
    case Date:
        // Plasma SDO allows more precision than just month/day/year
        // in an SDO date datatype, and using java.sql.Date will
        // truncate
        // here so use java.sql.Timestamp.
        result = java.sql.Types.TIMESTAMP;
        break;
    case DateTime:
        result = java.sql.Types.TIMESTAMP;
        // FIXME: so what SDO datatype maps to a SQL timestamp??
        break;
    case Decimal:
        result = java.sql.Types.DECIMAL;
        break;
    case Bytes:
        // FIXME: how do we know whether a Blob here
        result = java.sql.Types.VARBINARY;
        break;
    case Byte:
        result = java.sql.Types.VARBINARY;
        break;
    case Boolean:
        result = java.sql.Types.BOOLEAN;
        break;
    case Character:
        result = java.sql.Types.CHAR;
        break;
    case Double:
        result = java.sql.Types.DOUBLE;
        break;
    case Float:
        result = java.sql.Types.FLOAT;
        break;
    case Int:
        result = java.sql.Types.INTEGER;
        break;
    case Integer:
        result = java.sql.Types.BIGINT;
        break;
    case Long:
        result = java.sql.Types.INTEGER; // FIXME: no JDBC long??
        break;
    case Short:
        result = java.sql.Types.SMALLINT;
        break;
    case Object:
    default:
        result = java.sql.Types.VARCHAR;
        break;
    }
    return result;
}

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 w  w.  j  a  va  2  s . c o  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;
    }
    }
}

From source file:com.alibaba.otter.node.etl.extract.DatabaseExtractorTest.java

private List<EventColumn> getColumn(int value) {
    List<EventColumn> result = new ArrayList<EventColumn>();
    result.add(buildColumn("id", Types.INTEGER, "" + value, true, false));
    result.add(buildColumn("name", Types.VARCHAR, "ljh_" + value, true, false));

    result.add(buildColumn("alias_name", Types.CHAR, "hello_" + value, false, false));
    result.add(buildColumn("amount", Types.DECIMAL, "100.01", false, false));
    result.add(buildColumn("text_b", Types.BLOB, "[116,101,120,116,95,98]", false, false));
    result.add(buildColumn("text_c", Types.CLOB, "", false, false));
    result.add(buildColumn("curr_date", Types.DATE, "2011-01-01", false, false));
    result.add(buildColumn("gmt_create", Types.TIMESTAMP, "2011-01-01 11:11:11", false, false));
    result.add(buildColumn("gmt_modify", Types.TIMESTAMP, "2011-01-01 11:11:11", false, false));
    return result;
}