Example usage for java.sql Types DOUBLE

List of usage examples for java.sql Types DOUBLE

Introduction

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

Prototype

int DOUBLE

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

Click Source Link

Document

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

Usage

From source file:org.sakaiproject.webservices.SakaiReport.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   w  ww  .  ja va  2  s.  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;
    case Types.VARBINARY:
    case Types.BINARY:
        value = handleRaw(rs.getBytes(colIndex));
        break;
    default:
        value = "";
    }

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

    return value;

}

From source file:org.brucalipto.sqlutil.SQLManager.java

protected int executeSimpleQuery(final String preparedStatement, final SQLParameter[] params) {
    final SQLParameter[] parameters;
    if (params == null) {
        parameters = new SQLParameter[0];
        log.debug("Going to execute a query without parameters.");
    } else {//  w  ww.ja  va  2s  . c o  m
        parameters = (SQLParameter[]) params.clone();
    }
    Connection dbConn = null;
    PreparedStatement pstmt = null;
    try {
        if (this.dataSource != null) {
            dbConn = this.dataSource.getConnection();
        } else {
            dbConn = this.connection;
        }
        pstmt = dbConn.prepareStatement(preparedStatement);
        for (int i = 0; i < parameters.length; i++) {
            final SQLParameter param = parameters[i];
            log.debug((i + 1) + ") Going to add parameter " + param);
            final int sqlType = param.getSqlType();
            final Object paramValue = param.getValue();
            if (paramValue == null) {
                pstmt.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                pstmt.setString(i + 1, (String) paramValue);
                break;
            case Types.INTEGER:
                if (paramValue instanceof Integer) {
                    pstmt.setInt(i + 1, ((Integer) paramValue).intValue());
                } else if (paramValue instanceof Long) {
                    pstmt.setLong(i + 1, ((Long) paramValue).longValue());
                }
                break;
            case Types.DATE:
                pstmt.setDate(i + 1, (Date) paramValue);
                break;
            case Types.BOOLEAN:
                pstmt.setBoolean(i + 1, ((Boolean) paramValue).booleanValue());
                break;
            case Types.CHAR:
                pstmt.setString(i + 1, ((Character) paramValue).toString());
                break;
            case Types.DOUBLE:
                pstmt.setDouble(i + 1, ((Double) paramValue).doubleValue());
                break;
            case Types.FLOAT:
                pstmt.setFloat(i + 1, ((Float) paramValue).floatValue());
                break;
            case Types.TIMESTAMP:
                pstmt.setTimestamp(i + 1, (Timestamp) paramValue);
                break;
            default:
                pstmt.setObject(i + 1, paramValue);
                break;
            }
        }

        int result = pstmt.executeUpdate();
        log.debug("Prepared statement '" + preparedStatement + "' correctly executed (" + result + ")");
        return result;
    } catch (SQLException e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } catch (Exception e) {
        log.error("Error executing prepared statement '" + preparedStatement + "'", e);
    } finally {
        closeResources(pstmt, dbConn);
    }

    return -1;
}

From source file:fll.web.admin.UploadSubjectiveData.java

@SuppressFBWarnings(value = {
        "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING" }, justification = "columns are dynamic")
private static void saveCategoryData(final int currentTournament, final Connection connection,
        final Element scoreCategoryElement, final String categoryName, final ScoreCategory categoryElement)
        throws SQLException, ParseException {
    final List<AbstractGoal> goalDescriptions = categoryElement.getGoals();

    PreparedStatement insertPrep = null;
    PreparedStatement updatePrep = null;
    try {//from   www. j a  v a2  s .  c o m
        // prepare statements for update and insert

        final StringBuffer updateStmt = new StringBuffer();
        final StringBuffer insertSQLColumns = new StringBuffer();
        insertSQLColumns.append("INSERT INTO " + categoryName + " (TeamNumber, Tournament, Judge, NoShow");
        final StringBuffer insertSQLValues = new StringBuffer();
        insertSQLValues.append(") VALUES ( ?, ?, ?, ?");
        updateStmt.append("UPDATE " + categoryName + " SET NoShow = ? ");
        final int numGoals = goalDescriptions.size();
        for (final AbstractGoal goalDescription : goalDescriptions) {
            insertSQLColumns.append(", " + goalDescription.getName());
            insertSQLValues.append(", ?");
            updateStmt.append(", " + goalDescription.getName() + " = ?");
        }

        updateStmt.append(" WHERE TeamNumber = ? AND Tournament = ? AND Judge = ?");
        updatePrep = connection.prepareStatement(updateStmt.toString());
        insertPrep = connection
                .prepareStatement(insertSQLColumns.toString() + insertSQLValues.toString() + ")");
        // initialze the tournament
        insertPrep.setInt(2, currentTournament);
        updatePrep.setInt(numGoals + 3, currentTournament);

        for (final Element scoreElement : new NodelistElementCollectionAdapter(
                scoreCategoryElement.getElementsByTagName("score"))) {

            if (scoreElement.hasAttribute("modified")
                    && "true".equalsIgnoreCase(scoreElement.getAttribute("modified"))) {
                final int teamNumber = Utilities.NUMBER_FORMAT_INSTANCE
                        .parse(scoreElement.getAttribute("teamNumber")).intValue();

                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Saving score data for team: " + teamNumber);
                }

                final String judgeId = scoreElement.getAttribute("judge");
                final boolean noShow = Boolean.parseBoolean(scoreElement.getAttribute("NoShow"));
                updatePrep.setBoolean(1, noShow);
                insertPrep.setBoolean(4, noShow);

                insertPrep.setInt(1, teamNumber);
                updatePrep.setInt(numGoals + 2, teamNumber);
                insertPrep.setString(3, judgeId);
                updatePrep.setString(numGoals + 4, judgeId);

                int goalIndex = 0;
                for (final AbstractGoal goalDescription : goalDescriptions) {
                    final String goalName = goalDescription.getName();

                    final Element subscoreElement = SubjectiveUtils.getSubscoreElement(scoreElement, goalName);
                    if (null == subscoreElement) {
                        // no subscore element, no show or deleted
                        insertPrep.setNull(goalIndex + 5, Types.DOUBLE);
                        updatePrep.setNull(goalIndex + 2, Types.DOUBLE);
                    } else {
                        final String value = subscoreElement.getAttribute("value");
                        if (!value.trim().isEmpty()) {
                            insertPrep.setString(goalIndex + 5, value.trim());
                            updatePrep.setString(goalIndex + 2, value.trim());
                        } else {
                            insertPrep.setNull(goalIndex + 5, Types.DOUBLE);
                            updatePrep.setNull(goalIndex + 2, Types.DOUBLE);
                        }
                    }

                    ++goalIndex;
                } // end for

                // attempt the update first
                final int modifiedRows = updatePrep.executeUpdate();
                if (modifiedRows < 1) {
                    // do insert if nothing was updated
                    insertPrep.executeUpdate();
                }
            }
        }

    } finally {
        SQLFunctions.close(insertPrep);
        SQLFunctions.close(updatePrep);
    }

}

From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java

private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index)
        throws SQLException {
    switch (targetSqlType) {
    case Types.INTEGER:
        pstmt.setInt(index, Integer.parseInt(argument));
        break;// w  w  w. j av a  2 s.  c  om
    case Types.DECIMAL:
    case Types.NUMERIC:
        pstmt.setBigDecimal(index, new BigDecimal(argument));
        break;
    case Types.DOUBLE:
    case Types.FLOAT:
        pstmt.setDouble(index, Double.parseDouble(argument));
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        pstmt.setString(index, argument);
        break;
    case Types.BIT:
    case Types.BOOLEAN:
        pstmt.setBoolean(index, Boolean.parseBoolean(argument));
        break;
    case Types.BIGINT:
        pstmt.setLong(index, Long.parseLong(argument));
        break;
    case Types.DATE:
        pstmt.setDate(index, Date.valueOf(argument));
        break;
    case Types.REAL:
        pstmt.setFloat(index, Float.parseFloat(argument));
        break;
    case Types.TINYINT:
        pstmt.setByte(index, Byte.parseByte(argument));
        break;
    case Types.SMALLINT:
        pstmt.setShort(index, Short.parseShort(argument));
        break;
    case Types.TIMESTAMP:
        pstmt.setTimestamp(index, Timestamp.valueOf(argument));
        break;
    case Types.TIME:
        pstmt.setTime(index, Time.valueOf(argument));
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        pstmt.setBytes(index, argument.getBytes());
        break;
    case Types.NULL:
        pstmt.setNull(index, targetSqlType);
        break;
    default:
        pstmt.setObject(index, argument, targetSqlType);
    }
}

From source file:org.apache.cassandra.cql.jdbc.HandleObjects.java

public static final ByteBuffer makeBytes(Object object, int baseType, int scaleOrLength) throws SQLException {
    Class<? extends Object> objectClass = object.getClass();
    boolean isCollection = (Collection.class.isAssignableFrom(objectClass));
    int targetSqlType = isCollection ? Types.OTHER : baseType;
    // Type check first
    switch (targetSqlType) {
    case Types.TINYINT:
        // Only Numeric classes, Strings and Booleans are supported for transformation to TINYINT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "TINYINT");
        break;//from ww  w.ja v  a 2  s .  co m

    case Types.SMALLINT:
        // Only Numeric classes, Strings and Booleans are supported for transformation to SMALLINT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "SMALLINT");
        break;

    case Types.INTEGER:
        // Only Numeric classes, Strings and Booleans are supported for transformation to INTEGER
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "INTEGER");
        break;

    case Types.BIGINT:
        // Only Numeric classes, Strings and Booleans are supported for transformation to BIGINT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "BIGINT");
        break;

    case Types.REAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
        // Only Numeric classes Strings and Booleans are supported for transformation to REAL,FLOAT,DOUBLE,DECIMAL
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "the floating point types");
        break;

    case Types.NUMERIC:
        //NB This as a special case variation for Cassandra!! NUMERIC is transformed to java BigInteger (varint CQL type)
        //
        // Only Numeric classes Strings and Booleans are supported for transformation to NUMERIC
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "NUMERIC");
        break;

    case Types.BIT:
        // Only Numeric classes Strings and Booleans are supported for transformation to BIT
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "BIT");
        break;

    case Types.BOOLEAN:
        // Only Numeric classes Strings and Booleans are supported for transformation to BOOLEAN
        if (!(objectClass == String.class || objectClass == Boolean.class
                || Number.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "BOOLEAN");
        break;

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.NVARCHAR:
    case Types.LONGNVARCHAR:
        if (!objectClass.isAssignableFrom(String.class))
            throw makeBadMapping(objectClass, "String", "the various VARCHAR types");
        break;

    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        if (!(objectClass.isAssignableFrom(ByteBuffer.class) || objectClass.getSimpleName().equals("byte[]")))
            throw makeBadMapping(objectClass, "ByteBuffer or byte[]", "the BINARY Types");
        break;

    case Types.DATE:
        if (!(objectClass == String.class || objectClass == java.util.Date.class || objectClass == Date.class
                || objectClass == Timestamp.class))
            throw makeBadMapping(objectClass, "String, Date(java and sql) or Timestamp types", "DATE");
        break;

    case Types.TIME:
        if (!(objectClass == String.class || objectClass == java.util.Date.class || objectClass == Time.class
                || objectClass == Timestamp.class))
            throw makeBadMapping(objectClass, "String, Date (java), Time or Timestamp types", "TIME");
        break;

    case Types.TIMESTAMP:
        if (!(objectClass == String.class || objectClass == java.util.Date.class || objectClass == Date.class
                || objectClass == Timestamp.class))
            throw makeBadMapping(objectClass, "String, Date(java and sql) or Timestamp types", "TIMESTAMP");
        break;

    case Types.DATALINK:
        if (objectClass != URL.class)
            throw makeBadMapping(objectClass, "a URL type", "DATALINK");
        break;

    case Types.JAVA_OBJECT:
        break;

    case Types.OTHER:
        // Only Collection classes for transformation to OTHER
        if (!(List.class.isAssignableFrom(object.getClass()) || Set.class.isAssignableFrom(object.getClass())
                || Map.class.isAssignableFrom(object.getClass())))
            throw makeBadMapping(objectClass, STR_BOOL_NUMERIC, "OTHER");
        break;

    case Types.ROWID:
        if (objectClass != RowId.class)
            throw makeBadMapping(objectClass, "a RowId type", "ROWID");
        break;

    default:
        throw new SQLNonTransientException("Unsupported transformation to Jdbc Type: " + targetSqlType);
    }

    // see if we can map to an supported Type
    switch (targetSqlType) {
    case Types.BIT:
        BigInteger bitvalue = objectToBITorTINYINTorSMALLINTorNUMERIC(objectClass, object);
        assert bitvalue != null;
        return JdbcInteger.instance.decompose((bitvalue == BigInteger.ZERO) ? BigInteger.ZERO : BigInteger.ONE);

    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.NUMERIC:
        BigInteger varint = objectToBITorTINYINTorSMALLINTorNUMERIC(objectClass, object);
        assert varint != null;
        return JdbcInteger.instance.decompose(varint);

    case Types.INTEGER:
        Integer value = objectToINTEGER(objectClass, object);
        assert value != null;
        return JdbcInt32.instance.decompose(value);

    case Types.BIGINT:
        Long longvalue = objectToBIGINT(objectClass, object);
        assert longvalue != null;
        return JdbcLong.instance.decompose(longvalue);

    case Types.BOOLEAN:
        Boolean bool = objectToBOOLEAN(objectClass, object);
        assert bool != null;
        return JdbcBoolean.instance.decompose(bool);

    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    case Types.NVARCHAR:
    case Types.LONGNVARCHAR:
        return ByteBufferUtil.bytes((String) object);

    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        if (objectClass.isAssignableFrom(ByteBuffer.class)) {
            return ((ByteBuffer) object);
        } else if (objectClass.getSimpleName().equals("byte[]")) {
            return ByteBuffer.wrap((byte[]) object);
        } else
            return null; // this should not happen

    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
        Long millis = objectToDATEorTIMEorTIMESTAMP(objectClass, object);
        assert millis != null;
        return JdbcLong.instance.decompose(millis);

    case Types.DATALINK:
        String urlAsString = ((URL) object).toExternalForm();
        return JdbcUTF8.instance.decompose(urlAsString);

    case Types.JAVA_OBJECT:
        return javaObject(object);

    case Types.OTHER:
        if (List.class.isAssignableFrom(objectClass)) {
            return handleAsList(objectClass, object);
        } else if (Set.class.isAssignableFrom(objectClass)) {
            return handleAsSet(objectClass, object);
        } else if (Map.class.isAssignableFrom(objectClass)) {
            return handleAsMap(objectClass, object);
        } else
            return null;

    case Types.ROWID:
        byte[] bytes = ((RowId) object).getBytes();
        return ByteBuffer.wrap(bytes);

    default:
        LOG.warn("Unhandled JDBC type: " + targetSqlType);
        return null;
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java

@Override
@SuppressWarnings("boxing")
public Serializable getFromResultSet(ResultSet rs, int index, Column column) throws SQLException {
    int jdbcType = rs.getMetaData().getColumnType(index);
    if (column.getJdbcType() == Types.ARRAY && jdbcType != Types.ARRAY) {
        jdbcType = column.getJdbcBaseType();
    } else {//from w w w. j a v  a 2 s  .  co  m
        jdbcType = column.getJdbcType();
    }
    switch (jdbcType) {
    case Types.VARCHAR:
    case Types.CLOB:
        return getFromResultSetString(rs, index, column);
    case Types.BIT:
        return rs.getBoolean(index);
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
        return rs.getLong(index);
    case Types.DOUBLE:
        return rs.getDouble(index);
    case Types.TIMESTAMP:
        return getCalendarFromTimestamp(rs.getTimestamp(index));
    case Types.ARRAY:
        Array array = rs.getArray(index);
        if (array == null) {
            return null;
        }
        if (array.getBaseType() == Types.TIMESTAMP) {
            return getCalendarFromTimestamp((Timestamp[]) array.getArray());
        } else {
            return (Serializable) array.getArray();
        }
    case Types.OTHER:
        ColumnType type = column.getType();
        if (type.isId()) {
            return getId(rs, index);
        }
        throw new SQLException("Unhandled type: " + column.getType());
    }
    throw new SQLException(
            "Unhandled JDBC type: " + column.getJdbcType() + " for type " + column.getType().toString());
}

From source file:org.wso2.carbon.event.output.adaptor.mysql.MysqlEventAdaptorType.java

private TableInfo initializeDatabaseTableInfo(String tableName, String executionMode, String updateColumnKeys,
        Object message, OutputEventAdaptorConfiguration adaptorConfig) throws SQLException {
    TableInfo tableInfo = new TableInfo();
    tableInfo.setTableName(tableName);//w ww  .j a v  a 2s. c  o  m
    if (resourceBundle.getString(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE_UPDATE)
            .equalsIgnoreCase(executionMode)) {
        tableInfo.setUpdateMode(true);
    }
    Connection con = null;
    Statement stmt = null;

    try {
        DataSource dataSource = pooledDataSources.get(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        if (dataSource == null) {
            CarbonDataSource carbonDataSource = EventAdaptorValueHolder.getDataSourceService()
                    .getDataSource(adaptorConfig.getOutputProperties()
                            .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
            if (carbonDataSource == null) {
                throw new OutputEventAdaptorEventProcessingException(
                        "There is no any data-source found called : " + adaptorConfig.getOutputProperties()
                                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
            } else {
                dataSource = (DataSource) carbonDataSource.getDSObject();
                pooledDataSources.put(adaptorConfig, dataSource);
            }
        }

        con = dataSource.getConnection();
        String databaseName = con.getCatalog();
        tableInfo.setDatabaseName(databaseName);

        // create the table.
        StringBuilder statementBuilder = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
        statementBuilder.append(databaseName + "." + tableName);
        statementBuilder.append(" (");
        boolean appendComma = false;
        for (Map.Entry<String, Object> entry : (((Map<String, Object>) message).entrySet())) {
            if (appendComma) {
                statementBuilder.append(",");
            } else {
                appendComma = true;
            }
            statementBuilder.append(entry.getKey()).append("  ");
            if (entry.getValue() instanceof Integer) {
                statementBuilder.append("INT");
            } else if (entry.getValue() instanceof Long) {
                statementBuilder.append("BIGINT");
            } else if (entry.getValue() instanceof Float) {
                statementBuilder.append("FLOAT");
            } else if (entry.getValue() instanceof Double) {
                statementBuilder.append("DOUBLE");
            } else if (entry.getValue() instanceof String) {
                statementBuilder.append("VARCHAR(255)");
            } else if (entry.getValue() instanceof Boolean) {
                statementBuilder.append("BOOL");
            }
        }
        statementBuilder.append(")");

        stmt = con.createStatement();
        stmt.execute("CREATE SCHEMA IF NOT EXISTS " + databaseName);
        stmt.executeUpdate(statementBuilder.toString());

        ArrayList<Attribute> tableInsertColumnList = new ArrayList<Attribute>();
        statementBuilder = new StringBuilder("INSERT INTO ");
        statementBuilder.append(databaseName + "." + tableName);
        statementBuilder.append(" ( ");

        StringBuilder valuePositionsBuilder = new StringBuilder("");

        appendComma = false;
        DatabaseMetaData databaseMetaData = con.getMetaData();
        ResultSet rs = databaseMetaData.getColumns(databaseName, null, tableName, null);
        while (rs.next()) {
            AttributeType type = null;
            int colType = rs.getInt("DATA_TYPE");
            switch (colType) {
            case Types.VARCHAR:
                type = AttributeType.STRING;
                break;
            case Types.INTEGER:
                type = AttributeType.INT;
                break;
            case Types.BIGINT:
                type = AttributeType.LONG;
                break;
            case Types.DOUBLE:
                type = AttributeType.DOUBLE;
                break;
            case Types.FLOAT:
                type = AttributeType.FLOAT;
                break;
            case Types.TINYINT:
            case Types.BOOLEAN:
            case MysqlEventAdaptorConstants.TINYINT_MYSQL_VALUE:
                type = AttributeType.BOOL;
                break;

            }
            Attribute attribute = new Attribute(rs.getString("COLUMN_NAME"), type);
            tableInsertColumnList.add(attribute);

            if (appendComma) {
                statementBuilder.append(",");
                valuePositionsBuilder.append(",");
            } else {
                appendComma = true;
            }
            statementBuilder.append(attribute.getName());
            valuePositionsBuilder.append("?");
        }
        statementBuilder.append(") VALUES (");
        statementBuilder.append(valuePositionsBuilder.toString());
        statementBuilder.append(")");
        tableInfo.setPreparedInsertStatement(statementBuilder.toString());
        tableInfo.setInsertColumnOrder(tableInsertColumnList);

        if (executionMode.equalsIgnoreCase(
                resourceBundle.getString(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_EXECUTION_MODE_UPDATE))) {

            // existence check query.
            StringBuilder existenceQueryBuilder = new StringBuilder("SELECT 1 FROM ");
            existenceQueryBuilder.append(databaseName + "." + tableName);
            existenceQueryBuilder.append(" WHERE ");
            String[] queryAttributes = updateColumnKeys.trim().split(",");
            ArrayList<Attribute> queryAttributeList = new ArrayList<Attribute>(queryAttributes.length);

            for (int i = 0; i < queryAttributes.length; i++) {
                if (i > 0) {
                    existenceQueryBuilder.append(" AND ");
                }
                existenceQueryBuilder.append(queryAttributes[i]);
                existenceQueryBuilder.append(" = ? ");
                for (Attribute at : tableInfo.getInsertColumnOrder()) {
                    if (queryAttributes[i].equalsIgnoreCase(at.getName())) {
                        queryAttributeList.add(at);
                        break;
                    }
                }
            }
            tableInfo.setExistenceCheckColumnOrder(queryAttributeList);
            tableInfo.setPreparedExistenceCheckStatement(existenceQueryBuilder.toString());

            // update query.
            StringBuilder updateQueryBuilder = new StringBuilder("UPDATE  ");
            ArrayList<Attribute> updateAttributes = new ArrayList<Attribute>();
            updateQueryBuilder.append(tableInfo.getDatabaseName() + "." + tableInfo.getTableName());
            updateQueryBuilder.append(" SET ");
            appendComma = false;
            for (Attribute at : tableInfo.getInsertColumnOrder()) {
                if (!tableInfo.getExistenceCheckColumnOrder().contains(at)) {
                    if (appendComma) {
                        updateQueryBuilder.append(" , ");
                    }
                    updateQueryBuilder.append(at.getName());
                    updateQueryBuilder.append(" = ? ");
                    updateAttributes.add(at);
                    appendComma = true;
                }
            }
            updateQueryBuilder.append(" WHERE ");
            boolean appendAnd = false;
            for (Attribute at : tableInfo.getExistenceCheckColumnOrder()) {
                if (appendAnd) {
                    updateQueryBuilder.append(" AND ");
                }
                updateQueryBuilder.append(at.getName());
                updateQueryBuilder.append(" = ? ");
                updateAttributes.add(at);
                appendAnd = true;
            }
            tableInfo.setUpdateColumnOrder(updateAttributes);
            tableInfo.setPreparedUpdateStatement(updateQueryBuilder.toString());

        }
        return tableInfo;
    } catch (SQLException e) {
        pooledDataSources.remove(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        log.error("error while initializing the table", e);
    } catch (DataSourceException e) {
        pooledDataSources.remove(adaptorConfig.getOutputProperties()
                .get(MysqlEventAdaptorConstants.ADAPTOR_MYSQL_DATASOURCE_NAME));
        log.error("error while accessing the datasource:", e);
    } finally {
        cleanupConnections(stmt, con);
    }
    return null;
}

From source file:com.opengamma.masterdb.position.DbPositionMaster.java

/**
 * Inserts a new document.//  w w w.ja  v a2  s.  c  o m
 * 
 * @param document the document, not null
 * @return the new document, not null
 */
@Override
protected PositionDocument insert(final PositionDocument document) {
    ArgumentChecker.notNull(document.getPosition(), "document.position");
    ArgumentChecker.notNull(document.getPosition().getQuantity(), "document.position.quantity");
    for (final ManageableTrade trade : document.getPosition().getTrades()) {
        ArgumentChecker.notNull(trade.getQuantity(), "position.trade.quantity");
        ArgumentChecker.notNull(trade.getCounterpartyExternalId(), "position.trade.counterpartyexternalid");
        ArgumentChecker.notNull(trade.getTradeDate(), "position.trade.tradedate");
    }

    try (Timer.Context context = _insertTimer.time()) {
        final long positionId = nextId("pos_master_seq");
        final long positionOid = (document.getUniqueId() != null ? extractOid(document.getUniqueId())
                : positionId);
        final UniqueId positionUid = createUniqueId(positionOid, positionId);
        final ManageablePosition position = document.getPosition();

        // the arguments for inserting into the position table
        final DbMapSqlParameterSource docArgs = new DbMapSqlParameterSource()
                .addValue("position_id", positionId).addValue("position_oid", positionOid)
                .addTimestamp("ver_from_instant", document.getVersionFromInstant())
                .addTimestampNullFuture("ver_to_instant", document.getVersionToInstant())
                .addTimestamp("corr_from_instant", document.getCorrectionFromInstant())
                .addTimestampNullFuture("corr_to_instant", document.getCorrectionToInstant())
                .addValue("quantity", position.getQuantity(), Types.DECIMAL)
                .addValue("provider_scheme",
                        position.getProviderId() != null ? position.getProviderId().getScheme().getName()
                                : null,
                        Types.VARCHAR)
                .addValue("provider_value",
                        position.getProviderId() != null ? position.getProviderId().getValue() : null,
                        Types.VARCHAR);

        // the arguments for inserting into the pos_attribute table
        final List<DbMapSqlParameterSource> posAttrList = Lists.newArrayList();
        for (final Entry<String, String> entry : position.getAttributes().entrySet()) {
            final long posAttrId = nextId("pos_trade_attr_seq");
            final DbMapSqlParameterSource posAttrArgs = new DbMapSqlParameterSource()
                    .addValue("attr_id", posAttrId).addValue("pos_id", positionId)
                    .addValue("pos_oid", positionOid).addValue("key", entry.getKey())
                    .addValue("value", entry.getValue());
            posAttrList.add(posAttrArgs);
        }

        // the arguments for inserting into the idkey tables
        final List<DbMapSqlParameterSource> posAssocList = new ArrayList<DbMapSqlParameterSource>();
        final Set<Pair<String, String>> schemeValueSet = Sets.newHashSet();
        for (final ExternalId id : position.getSecurityLink().getAllExternalIds()) {
            final DbMapSqlParameterSource assocArgs = new DbMapSqlParameterSource()
                    .addValue("position_id", positionId).addValue("key_scheme", id.getScheme().getName())
                    .addValue("key_value", id.getValue());
            posAssocList.add(assocArgs);
            schemeValueSet.add(Pair.of(id.getScheme().getName(), id.getValue()));
        }

        // the arguments for inserting into the trade table
        final List<DbMapSqlParameterSource> tradeList = Lists.newArrayList();
        final List<DbMapSqlParameterSource> tradeAssocList = Lists.newArrayList();
        final List<DbMapSqlParameterSource> tradeAttributeList = Lists.newArrayList();
        for (final ManageableTrade trade : position.getTrades()) {
            final long tradeId = nextId("pos_master_seq");
            final long tradeOid = (trade.getUniqueId() != null ? extractOid(trade.getUniqueId()) : tradeId);
            final ExternalId counterpartyId = trade.getCounterpartyExternalId();

            final DbMapSqlParameterSource tradeArgs = new DbMapSqlParameterSource()
                    .addValue("trade_id", tradeId).addValue("trade_oid", tradeOid)
                    .addValue("position_id", positionId).addValue("position_oid", positionOid)
                    .addValue("quantity", trade.getQuantity()).addDate("trade_date", trade.getTradeDate())
                    .addTimeAllowNull("trade_time",
                            trade.getTradeTime() != null ? trade.getTradeTime().toLocalTime() : null)
                    .addValue("zone_offset",
                            trade.getTradeTime() != null ? trade.getTradeTime().getOffset().getTotalSeconds()
                                    : null,
                            Types.INTEGER)
                    .addValue("cparty_scheme", counterpartyId.getScheme().getName())
                    .addValue("cparty_value", counterpartyId.getValue())
                    .addValue("provider_scheme",
                            position.getProviderId() != null ? position.getProviderId().getScheme().getName()
                                    : null,
                            Types.VARCHAR)
                    .addValue("provider_value",
                            position.getProviderId() != null ? position.getProviderId().getValue() : null,
                            Types.VARCHAR)
                    .addValue("premium_value", trade.getPremium(), Types.DOUBLE)
                    .addValue("premium_currency",
                            trade.getPremiumCurrency() != null ? trade.getPremiumCurrency().getCode() : null,
                            Types.VARCHAR)
                    .addDateAllowNull("premium_date", trade.getPremiumDate())
                    .addTimeAllowNull("premium_time",
                            (trade.getPremiumTime() != null ? trade.getPremiumTime().toLocalTime() : null))
                    .addValue("premium_zone_offset",
                            trade.getPremiumTime() != null
                                    ? trade.getPremiumTime().getOffset().getTotalSeconds()
                                    : null,
                            Types.INTEGER);
            tradeList.add(tradeArgs);

            // trade attributes
            final Map<String, String> attributes = new HashMap<String, String>(trade.getAttributes());
            for (final Entry<String, String> entry : attributes.entrySet()) {
                final long tradeAttrId = nextId("pos_trade_attr_seq");
                final DbMapSqlParameterSource tradeAttributeArgs = new DbMapSqlParameterSource()
                        .addValue("attr_id", tradeAttrId).addValue("trade_id", tradeId)
                        .addValue("trade_oid", tradeOid).addValue("key", entry.getKey())
                        .addValue("value", entry.getValue());
                tradeAttributeList.add(tradeAttributeArgs);
            }

            // set the trade uniqueId
            final UniqueId tradeUid = createUniqueId(tradeOid, tradeId);
            IdUtils.setInto(trade, tradeUid);
            trade.setParentPositionId(positionUid);
            for (final ExternalId id : trade.getSecurityLink().getAllExternalIds()) {
                final DbMapSqlParameterSource assocArgs = new DbMapSqlParameterSource()
                        .addValue("trade_id", tradeId).addValue("key_scheme", id.getScheme().getName())
                        .addValue("key_value", id.getValue());
                tradeAssocList.add(assocArgs);
                schemeValueSet.add(Pair.of(id.getScheme().getName(), id.getValue()));
            }
        }

        final List<DbMapSqlParameterSource> idKeyList = new ArrayList<DbMapSqlParameterSource>();
        final String sqlSelectIdKey = getElSqlBundle().getSql("SelectIdKey");
        for (final Pair<String, String> pair : schemeValueSet) {
            final DbMapSqlParameterSource idkeyArgs = new DbMapSqlParameterSource()
                    .addValue("key_scheme", pair.getFirst()).addValue("key_value", pair.getSecond());
            if (getJdbcTemplate().queryForList(sqlSelectIdKey, idkeyArgs).isEmpty()) {
                // select avoids creating unecessary id, but id may still not be used
                final long idKeyId = nextId("pos_idkey_seq");
                idkeyArgs.addValue("idkey_id", idKeyId);
                idKeyList.add(idkeyArgs);
            }
        }

        final String sqlDoc = getElSqlBundle().getSql("Insert", docArgs);
        final String sqlIdKey = getElSqlBundle().getSql("InsertIdKey");
        final String sqlPosition2IdKey = getElSqlBundle().getSql("InsertPosition2IdKey");
        final String sqlTrade = getElSqlBundle().getSql("InsertTrade");
        final String sqlTrade2IdKey = getElSqlBundle().getSql("InsertTrade2IdKey");
        final String sqlPositionAttributes = getElSqlBundle().getSql("InsertPositionAttributes");
        final String sqlTradeAttributes = getElSqlBundle().getSql("InsertTradeAttributes");
        getJdbcTemplate().update(sqlDoc, docArgs);
        getJdbcTemplate().batchUpdate(sqlIdKey,
                idKeyList.toArray(new DbMapSqlParameterSource[idKeyList.size()]));
        getJdbcTemplate().batchUpdate(sqlPosition2IdKey,
                posAssocList.toArray(new DbMapSqlParameterSource[posAssocList.size()]));
        getJdbcTemplate().batchUpdate(sqlTrade,
                tradeList.toArray(new DbMapSqlParameterSource[tradeList.size()]));
        getJdbcTemplate().batchUpdate(sqlTrade2IdKey,
                tradeAssocList.toArray(new DbMapSqlParameterSource[tradeAssocList.size()]));
        getJdbcTemplate().batchUpdate(sqlPositionAttributes,
                posAttrList.toArray(new DbMapSqlParameterSource[posAttrList.size()]));
        getJdbcTemplate().batchUpdate(sqlTradeAttributes,
                tradeAttributeList.toArray(new DbMapSqlParameterSource[tradeAttributeList.size()]));

        // set the uniqueId
        position.setUniqueId(positionUid);
        document.setUniqueId(positionUid);
        return document;
    }
}

From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java

protected Object getObjectValue(String value, Column column, BinaryEncoding encoding, boolean useVariableDates,
        boolean fitToColumn) throws DecoderException {
    Object objectValue = value;/*from w  w w . ja v  a 2  s  .c  o m*/
    int type = column.getMappedTypeCode();
    if ((value == null || (getDdlBuilder().getDatabaseInfo().isEmptyStringNulled() && value.equals("")))
            && column.isRequired() && column.isOfTextType()) {
        objectValue = REQUIRED_FIELD_NULL_SUBSTITUTE;
    }
    if (value != null) {
        if (type == Types.DATE || type == Types.TIMESTAMP || type == Types.TIME) {
            objectValue = parseDate(type, value, useVariableDates);
        } else if (type == Types.CHAR) {
            String charValue = value.toString();
            if ((StringUtils.isBlank(charValue)
                    && getDdlBuilder().getDatabaseInfo().isBlankCharColumnSpacePadded())
                    || (StringUtils.isNotBlank(charValue)
                            && getDdlBuilder().getDatabaseInfo().isNonBlankCharColumnSpacePadded())) {
                objectValue = StringUtils.rightPad(value.toString(), column.getSizeAsInt(), ' ');
            }
        } else if (type == Types.BIGINT) {
            objectValue = parseBigInteger(value);
        } else if (type == Types.INTEGER || type == Types.SMALLINT || type == Types.BIT
                || type == Types.TINYINT) {
            objectValue = parseInteger(value);
        } else if (type == Types.NUMERIC || type == Types.DECIMAL || type == Types.FLOAT || type == Types.DOUBLE
                || type == Types.REAL) {
            objectValue = parseBigDecimal(value);
        } else if (type == Types.BOOLEAN) {
            objectValue = value.equals("1") ? Boolean.TRUE : Boolean.FALSE;
        } else if (!(column.getJdbcTypeName() != null
                && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOMETRY))
                && !(column.getJdbcTypeName() != null
                        && column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOGRAPHY))
                && (type == Types.BLOB || type == Types.LONGVARBINARY || type == Types.BINARY
                        || type == Types.VARBINARY ||
                        // SQLServer ntext type
                        type == -10)) {
            if (encoding == BinaryEncoding.NONE) {
                objectValue = value.getBytes();
            } else if (encoding == BinaryEncoding.BASE64) {
                objectValue = Base64.decodeBase64(value.getBytes());
            } else if (encoding == BinaryEncoding.HEX) {
                objectValue = Hex.decodeHex(value.toCharArray());
            }
        } else if (type == Types.ARRAY) {
            objectValue = createArray(column, value);
        }
    }
    if (objectValue instanceof String) {
        String stringValue = cleanTextForTextBasedColumns((String) objectValue);
        int size = column.getSizeAsInt();
        if (fitToColumn && size > 0 && stringValue.length() > size) {
            stringValue = stringValue.substring(0, size);
        }
        objectValue = stringValue;
    }

    return objectValue;

}

From source file:org.springframework.jdbc.support.JdbcUtils.java

/**
 * Check whether the given SQL type is numeric.
 * @param sqlType the SQL type to be checked
 * @return whether the type is numeric//from w ww .java 2s .  c  om
 */
public static boolean isNumeric(int sqlType) {
    return Types.BIT == sqlType || Types.BIGINT == sqlType || Types.DECIMAL == sqlType
            || Types.DOUBLE == sqlType || Types.FLOAT == sqlType || Types.INTEGER == sqlType
            || Types.NUMERIC == sqlType || Types.REAL == sqlType || Types.SMALLINT == sqlType
            || Types.TINYINT == sqlType;
}