Example usage for java.sql Types DATE

List of usage examples for java.sql Types DATE

Introduction

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

Prototype

int DATE

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

Click Source Link

Document

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

Usage

From source file:org.akaza.openclinica.dao.managestudy.StudyDAO.java

/**
 * <P>/*  w w  w . j av  a2  s. c o m*/
 * createStepOne, per the 'Detailed use case for administer system document
 * v1.0rc1' document. We insert the study in this method, and then update
 * the same study in the next three steps.
 * <P>
 * The next three steps, by the way, can then be used to update studies as
 * well.
 * 
 * @param sb
 *            Study bean about to be created.
 * @return same study bean with a primary key in the ID field.
 */
public StudyBean createStepOne(StudyBean sb) {
    HashMap variables = new HashMap();
    HashMap nullVars = new HashMap();
    sb.setId(this.findNextKey());
    variables.put(new Integer(1), new Integer(sb.getId()));
    if (sb.getParentStudyId() == 0) {
        nullVars.put(new Integer(2), new Integer(Types.INTEGER));
        variables.put(new Integer(2), null);
    } else {
        variables.put(new Integer(2), new Integer(sb.getParentStudyId()));
    }

    variables.put(new Integer(3), sb.getName());
    variables.put(new Integer(4), sb.getOfficialTitle());
    variables.put(new Integer(5), sb.getIdentifier());
    variables.put(new Integer(6), sb.getSecondaryIdentifier());
    variables.put(new Integer(7), sb.getSummary());
    variables.put(new Integer(8), sb.getPrincipalInvestigator());

    if (sb.getDatePlannedStart() == null) {
        nullVars.put(new Integer(9), new Integer(Types.DATE));
        variables.put(new Integer(9), null);
    } else {
        variables.put(new Integer(9), sb.getDatePlannedStart());
    }

    if (sb.getDatePlannedEnd() == null) {
        nullVars.put(new Integer(10), new Integer(Types.DATE));
        variables.put(new Integer(10), null);
    } else {
        variables.put(new Integer(10), sb.getDatePlannedEnd());
    }

    variables.put(new Integer(11), sb.getFacilityName());
    variables.put(new Integer(12), sb.getFacilityCity());
    variables.put(new Integer(13), sb.getFacilityState());
    variables.put(new Integer(14), sb.getFacilityZip());
    variables.put(new Integer(15), sb.getFacilityCountry());
    variables.put(new Integer(16), sb.getFacilityRecruitmentStatusKey());
    variables.put(new Integer(17), sb.getFacilityContactName());
    variables.put(new Integer(18), sb.getFacilityContactDegree());
    variables.put(new Integer(19), sb.getFacilityContactPhone());
    variables.put(new Integer(20), sb.getFacilityContactEmail());
    variables.put(new Integer(21), new Integer(sb.getStatus().getId()));
    // variables.put(new Integer(19), sb.getStatus())//need to get a
    // function
    // to get the id
    variables.put(new Integer(22), new java.util.Date());
    variables.put(new Integer(23), new Integer(sb.getOwnerId()));
    variables.put(new Integer(24), getValidOid(sb));
    variables.put(new Integer(25), sb.getEnvType().toString());
    // replace this with the owner id
    this.execute(digester.getQuery("createStepOne"), variables, nullVars);
    return sb;
}

From source file:architecture.ee.web.community.page.dao.jdbc.JdbcPageDao.java

private void insertPageVersion(Page page) {
    Date now = Calendar.getInstance().getTime();
    if (page.getVersionId() > 1) {
        page.setModifiedDate(now);/*ww w .  ja va2  s  .  c  o m*/
    }
    if (page.getPageState() == PageState.PUBLISHED) {
        // clean up on publish
        cleanupVersionsOnPublish(page);
    }

    // INSERT V2_PAGE_VERSION
    getExtendedJdbcTemplate().update(getBoundSql("ARCHITECTURE_COMMUNITY.INSERT_PAGE_VERSION").getSql(),
            new SqlParameterValue(Types.NUMERIC, page.getPageId()),
            new SqlParameterValue(Types.NUMERIC, page.getVersionId()),
            new SqlParameterValue(Types.VARCHAR, page.getPageState().name().toLowerCase()),
            new SqlParameterValue(Types.VARCHAR, page.getTitle()),
            page.getSummary() == null ? new SqlParameterValue(Types.NULL, null)
                    : new SqlParameterValue(Types.VARCHAR, page.getSummary()),
            new SqlParameterValue(Types.NUMERIC,
                    page.getVersionId() <= 1 ? page.getUser().getUserId()
                            : SecurityHelper.getUser().getUserId()),
            new SqlParameterValue(Types.DATE, page.getCreationDate()),
            new SqlParameterValue(Types.DATE, page.getModifiedDate()));
}

From source file:com.webpagebytes.cms.local.WPBLocalDataStoreDao.java

private int buildStatementForInsertUpdate(Object obj, Set<String> ignoreFields,
        PreparedStatement preparedStatement, Connection connection)
        throws SQLException, WPBSerializerException {
    Class<? extends Object> kind = obj.getClass();
    Field[] fields = kind.getDeclaredFields();
    int fieldIndex = 0;
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];/*w w w  . ja va 2 s.  c  om*/
        field.setAccessible(true);
        boolean storeField = (field.getAnnotation(WPBAdminFieldKey.class) != null)
                || (field.getAnnotation(WPBAdminFieldStore.class) != null)
                || (field.getAnnotation(WPBAdminFieldTextStore.class) != null);
        if (storeField) {
            String fieldName = field.getName();
            if (ignoreFields != null && ignoreFields.contains(fieldName)) {
                continue;
            }
            fieldIndex = fieldIndex + 1;
            Object value = null;
            try {
                PropertyDescriptor pd = new PropertyDescriptor(fieldName, kind);
                value = pd.getReadMethod().invoke(obj);
            } catch (Exception e) {
                throw new WPBSerializerException("Cannot get property value", e);
            }
            if (field.getType() == Long.class) {
                Long valueLong = (Long) value;
                if (valueLong != null) {
                    preparedStatement.setLong(fieldIndex, valueLong);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.BIGINT);
                }
            } else if (field.getType() == String.class) {

                String valueString = (String) value;
                if (field.getAnnotation(WPBAdminFieldStore.class) != null
                        || field.getAnnotation(WPBAdminFieldKey.class) != null) {
                    if (valueString != null) {
                        preparedStatement.setString(fieldIndex, valueString);
                    } else {
                        preparedStatement.setNull(fieldIndex, Types.VARCHAR);
                    }
                } else if (field.getAnnotation(WPBAdminFieldTextStore.class) != null) {
                    if (valueString != null) {
                        Clob clob = connection.createClob();
                        clob.setString(1, valueString);
                        preparedStatement.setClob(fieldIndex, clob);
                    } else {
                        preparedStatement.setNull(fieldIndex, Types.CLOB);
                    }
                }
            } else if (field.getType() == Integer.class) {
                Integer valueInt = (Integer) value;
                if (valueInt != null) {
                    preparedStatement.setInt(fieldIndex, valueInt);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.INTEGER);
                }
            } else if (field.getType() == Date.class) {
                Date date = (Date) value;
                if (date != null) {
                    java.sql.Timestamp sqlDate = new java.sql.Timestamp(date.getTime());
                    preparedStatement.setTimestamp(fieldIndex, sqlDate);
                } else {
                    preparedStatement.setNull(fieldIndex, Types.DATE);
                }
            }
        }
    }
    return fieldIndex;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.TableContextUtil.java

/**
 * Determines if there are invalid values specified in the initial offset value
 * for columns.//  w w  w .j av a  2  s.c om
 */
//@VisibleForTesting
void checkForInvalidInitialOffsetValues(PushSource.Context context, List<Stage.ConfigIssue> issues,
        String qualifiedTableName, LinkedHashMap<String, Integer> offsetColumnToType,
        Map<String, String> offsetColumnToStartOffset) throws StageException {
    List<String> invalidInitialOffsetFieldAndValue = new ArrayList<>();
    offsetColumnToType.forEach((offsetColumn, offsetSqlType) -> {
        String initialOffsetValue = offsetColumnToStartOffset.get(offsetColumn);
        try {
            if (jdbcUtil.isSqlTypeOneOf(offsetSqlType, Types.DATE, Types.TIME, Types.TIMESTAMP)) {
                Long.valueOf(initialOffsetValue); //NOSONAR
            } else {
                //Use native field conversion strategy to conver string to specify type and get value
                Field.create(OffsetQueryUtil.SQL_TYPE_TO_FIELD_TYPE.get(offsetSqlType), initialOffsetValue)
                        .getValue();
            }
        } catch (IllegalArgumentException e) {
            LOG.error(Utils.format("Invalid Initial Offset Value {} for column {} in table {}",
                    initialOffsetValue, offsetColumn, qualifiedTableName), e);
            invalidInitialOffsetFieldAndValue.add(offsetColumn + " - " + initialOffsetValue);
        }
    });
    if (!invalidInitialOffsetFieldAndValue.isEmpty()) {
        throw new StageException(JdbcErrors.JDBC_72, qualifiedTableName,
                COMMA_JOINER.join(invalidInitialOffsetFieldAndValue));
    }
}

From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java

/**
 * Return a Prepared statement for the given Statement object, which is ready to be executed
 *
 * @param stmnt  SQL stataement to be executed
 * @param con    The connection to be used
 * @param msgCtx Current message context
 * @return a PreparedStatement/*from  w w w .j  a v a  2s  . com*/
 * @throws SQLException on error
 */
protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx)
        throws SQLException {

    SynapseLog synLog = getLog(msgCtx);

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Getting a connection from DataSource " + getDSName()
                + " and preparing statement : " + stmnt.getRawStatement());
    }

    if (con == null) {
        String msg = "Connection from DataSource " + getDSName() + " is null.";
        log.error(msg);
        throw new SynapseException(msg);
    }

    if (dataSource instanceof BasicDataSource) {

        BasicDataSource basicDataSource = (BasicDataSource) dataSource;
        int numActive = basicDataSource.getNumActive();
        int numIdle = basicDataSource.getNumIdle();
        String connectionId = Integer.toHexString(con.hashCode());

        DBPoolView dbPoolView = getDbPoolView();
        if (dbPoolView != null) {
            dbPoolView.setNumActive(numActive);
            dbPoolView.setNumIdle(numIdle);
            dbPoolView.updateConnectionUsage(connectionId);
        }

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("[ DB Connection : " + con + " ]");
            synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]");
            synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]");
            synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]");
        }
    }

    PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement());

    // set parameters if any
    List<Statement.Parameter> params = stmnt.getParameters();
    int column = 1;

    for (Statement.Parameter param : params) {
        if (param == null) {
            continue;
        }
        String value = (param.getPropertyName() != null ? param.getPropertyName()
                : param.getXpath().stringValueOf(msgCtx));

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : "
                    + param.getType() + "(see java.sql.Types for valid " + "types)");
        }

        switch (param.getType()) {
        // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR: {
            if (value != null && value.length() != 0) {
                ps.setString(column++, value);
            } else {
                ps.setString(column++, null);
            }
            break;
        }
        case Types.NUMERIC:
        case Types.DECIMAL: {
            if (value != null && value.length() != 0) {
                ps.setBigDecimal(column++, new BigDecimal(value));
            } else {
                ps.setBigDecimal(column++, null);
            }
            break;
        }
        case Types.BIT: {
            if (value != null && value.length() != 0) {
                ps.setBoolean(column++, Boolean.parseBoolean(value));
            } else {
                ps.setNull(column++, Types.BIT);
            }
            break;
        }
        case Types.TINYINT: {
            if (value != null && value.length() != 0) {
                ps.setByte(column++, Byte.parseByte(value));
            } else {
                ps.setNull(column++, Types.TINYINT);
            }
            break;
        }
        case Types.SMALLINT: {
            if (value != null && value.length() != 0) {
                ps.setShort(column++, Short.parseShort(value));
            } else {
                ps.setNull(column++, Types.SMALLINT);
            }
            break;
        }
        case Types.INTEGER: {
            if (value != null && value.length() != 0) {
                ps.setInt(column++, Integer.parseInt(value));
            } else {
                ps.setNull(column++, Types.INTEGER);
            }
            break;
        }
        case Types.BIGINT: {
            if (value != null && value.length() != 0) {
                ps.setLong(column++, Long.parseLong(value));
            } else {
                ps.setNull(column++, Types.BIGINT);
            }
            break;
        }
        case Types.REAL: {
            if (value != null && value.length() != 0) {
                ps.setFloat(column++, Float.parseFloat(value));
            } else {
                ps.setNull(column++, Types.REAL);
            }
            break;
        }
        case Types.FLOAT: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.FLOAT);
            }
            break;
        }
        case Types.DOUBLE: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.DOUBLE);
            }
            break;
        }
        // skip BINARY, VARBINARY and LONGVARBINARY
        case Types.DATE: {
            if (value != null && value.length() != 0) {
                ps.setDate(column++, Date.valueOf(value));
            } else {
                ps.setNull(column++, Types.DATE);
            }
            break;
        }
        case Types.TIME: {
            if (value != null && value.length() != 0) {
                ps.setTime(column++, Time.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIME);
            }
            break;
        }
        case Types.TIMESTAMP: {
            if (value != null && value.length() != 0) {
                ps.setTimestamp(column++, Timestamp.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIMESTAMP);
            }
            break;
        }
        // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT
        default: {
            String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : "
                    + column + " and statement : " + stmnt.getRawStatement()
                    + " used by a DB mediator against DataSource : " + getDSName()
                    + " (see java.sql.Types for valid type values)";
            handleException(msg, msgCtx);
        }
        }
    }

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement()
                + " against DataSource : " + getDSName());
    }
    return ps;
}

From source file:org.apache.drill.test.framework.Utils.java

public static String getSqlResult(ResultSet resultSet) throws SQLException {
    StringBuffer stringBuffer = new StringBuffer();
    List columnLabels = new ArrayList<String>();

    try {//from  www. j a v a 2 s. c o  m
        int columnCount = resultSet.getMetaData().getColumnCount();
        for (int i = 1; i <= columnCount; i++) {
            columnLabels.add(resultSet.getMetaData().getColumnLabel(i));
        }
        List<Integer> types = Lists.newArrayList();
        for (int i = 1; i <= columnCount; i++) {
            types.add(resultSet.getMetaData().getColumnType(i));
        }

        LOG.debug("Result set data types:");
        LOG.debug(Utils.getTypesInStrings(types));
        stringBuffer.append(new ColumnList(types, columnLabels).toString() + "\n");

        while (resultSet.next()) {
            List<Object> values = Lists.newArrayList();
            for (int i = 1; i <= columnCount; i++) {
                try {
                    if (resultSet.getObject(i) == null) {
                        values.add(null);
                        continue;
                    }
                    if (resultSet.getMetaData().getColumnType(i) == Types.NVARCHAR) {
                        values.add(new String(resultSet.getBytes(i), "UTF-16"));
                    } else {
                        values.add(new String(resultSet.getBytes(i), "UTF-8"));
                    }
                } catch (Exception e) {
                    if (resultSet.getMetaData().getColumnType(i) == Types.DATE) {
                        values.add(resultSet.getDate(i));
                    } else {
                        values.add(resultSet.getObject(i));
                    }
                }
            }
            stringBuffer.append(new ColumnList(types, values).toString() + "\n");
        }
    } catch (IllegalArgumentException | IllegalAccessException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
    return stringBuffer.toString();
}

From source file:org.sakaiproject.nakamura.lite.storage.jdbc.WideColumnIndexer.java

private int toSqlType(String columnFamily, String k) {
    String type = indexColumnsTypes.get(columnFamily + ":" + k);
    if (type == null) {
        return Types.VARCHAR;
    } else if (type.startsWith("String")) {
        return Types.VARCHAR;
    } else if (type.startsWith("int")) {
        return Types.INTEGER;
    } else if (type.startsWith("Date")) {
        return Types.DATE;
    }//from w w w.ja  va  2  s.c om
    return Types.VARCHAR;
}

From source file:com.streamsets.pipeline.stage.processor.parser.sql.SqlParserProcessor.java

private void resolveSchema(SchemaAndTable schemaAndTable) throws StageException {
    Map<String, Integer> columns = new HashMap<>();
    String schema = schemaAndTable.getSchema();
    String table = schemaAndTable.getTable();
    try (Statement s = connection.createStatement()) {
        ResultSetMetaData md = s//from  w  ww .ja v a 2 s . c om
                .executeQuery(Utils.format("SELECT * FROM {}{} WHERE 1 = 0",
                        StringUtils.isNotEmpty(schema) ? "\"" + schema + "\"." : "", "\"" + table + "\""))
                .getMetaData();
        int colCount = md.getColumnCount();
        for (int i = 1; i <= colCount; i++) {
            int colType = md.getColumnType(i);
            String colName = md.getColumnName(i);
            if (!configBean.caseSensitive) {
                colName = colName.toUpperCase();
            }
            if (colType == Types.DATE || colType == Types.TIME || colType == Types.TIMESTAMP) {
                dateTimeColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>());
                dateTimeColumns.get(schemaAndTable).put(colName, md.getColumnTypeName(i));
            }

            if (colType == Types.DECIMAL || colType == Types.NUMERIC) {
                decimalColumns.computeIfAbsent(schemaAndTable, k -> new HashMap<>()).put(colName,
                        new PrecisionAndScale(md.getPrecision(i), md.getScale(i)));
            }
            columns.put(md.getColumnName(i), md.getColumnType(i));
        }
        tableSchemas.put(schemaAndTable, columns);
    } catch (SQLException ex) {
        throw new StageException(JDBC_00, configBean.hikariConfigBean.connectionString);
    }
}

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

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column/*w ww .  ja  va 2 s.co m*/
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

From source file:org.springframework.jdbc.core.StatementCreatorUtils.java

private static void setValue(PreparedStatement ps, int paramIndex, int sqlType, @Nullable String typeName,
        @Nullable Integer scale, Object inValue) throws SQLException {

    if (inValue instanceof SqlTypeValue) {
        ((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName);
    } else if (inValue instanceof SqlValue) {
        ((SqlValue) inValue).setValue(ps, paramIndex);
    } else if (sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR) {
        ps.setString(paramIndex, inValue.toString());
    } else if (sqlType == Types.NVARCHAR || sqlType == Types.LONGNVARCHAR) {
        ps.setNString(paramIndex, inValue.toString());
    } else if ((sqlType == Types.CLOB || sqlType == Types.NCLOB) && isStringValue(inValue.getClass())) {
        String strVal = inValue.toString();
        if (strVal.length() > 4000) {
            // Necessary for older Oracle drivers, in particular when running against an Oracle 10 database.
            // Should also work fine against other drivers/databases since it uses standard JDBC 4.0 API.
            if (sqlType == Types.NCLOB) {
                ps.setNClob(paramIndex, new StringReader(strVal), strVal.length());
            } else {
                ps.setClob(paramIndex, new StringReader(strVal), strVal.length());
            }//w ww.j  a v a2s .  c o  m
            return;
        } else {
            // Fallback: setString or setNString binding
            if (sqlType == Types.NCLOB) {
                ps.setNString(paramIndex, strVal);
            } else {
                ps.setString(paramIndex, strVal);
            }
        }
    } else if (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) {
        if (inValue instanceof BigDecimal) {
            ps.setBigDecimal(paramIndex, (BigDecimal) inValue);
        } else if (scale != null) {
            ps.setObject(paramIndex, inValue, sqlType, scale);
        } else {
            ps.setObject(paramIndex, inValue, sqlType);
        }
    } else if (sqlType == Types.BOOLEAN) {
        if (inValue instanceof Boolean) {
            ps.setBoolean(paramIndex, (Boolean) inValue);
        } else {
            ps.setObject(paramIndex, inValue, Types.BOOLEAN);
        }
    } else if (sqlType == Types.DATE) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Date) {
                ps.setDate(paramIndex, (java.sql.Date) inValue);
            } else {
                ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.DATE);
        }
    } else if (sqlType == Types.TIME) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Time) {
                ps.setTime(paramIndex, (java.sql.Time) inValue);
            } else {
                ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.TIME);
        }
    } else if (sqlType == Types.TIMESTAMP) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Timestamp) {
                ps.setTimestamp(paramIndex, (java.sql.Timestamp) inValue);
            } else {
                ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.TIMESTAMP);
        }
    } else if (sqlType == SqlTypeValue.TYPE_UNKNOWN || (sqlType == Types.OTHER
            && "Oracle".equals(ps.getConnection().getMetaData().getDatabaseProductName()))) {
        if (isStringValue(inValue.getClass())) {
            ps.setString(paramIndex, inValue.toString());
        } else if (isDateValue(inValue.getClass())) {
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
        } else {
            // Fall back to generic setObject call without SQL type specified.
            ps.setObject(paramIndex, inValue);
        }
    } else {
        // Fall back to generic setObject call with SQL type specified.
        ps.setObject(paramIndex, inValue, sqlType);
    }
}