Example usage for java.sql PreparedStatement setDate

List of usage examples for java.sql PreparedStatement setDate

Introduction

In this page you can find the example usage for java.sql PreparedStatement setDate.

Prototype

void setDate(int parameterIndex, java.sql.Date x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

Usage

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

public int setToPreparedStatement(PreparedStatement ps, int i, Serializable object) throws SQLException {
    if (object instanceof Calendar) {
        Calendar cal = (Calendar) object;
        ps.setTimestamp(i, dialect.getTimestampFromCalendar(cal), cal);
    } else if (object instanceof java.sql.Date) {
        ps.setDate(i, (java.sql.Date) object);
    } else if (object instanceof Long) {
        ps.setLong(i, ((Long) object).longValue());
    } else if (object instanceof WrappedId) {
        dialect.setId(ps, i, object.toString());
    } else if (object instanceof Object[]) {
        int jdbcType;
        if (object instanceof String[]) {
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.STRING).jdbcType;
        } else if (object instanceof Boolean[]) {
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.BOOLEAN).jdbcType;
        } else if (object instanceof Long[]) {
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.LONG).jdbcType;
        } else if (object instanceof Double[]) {
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.DOUBLE).jdbcType;
        } else if (object instanceof java.sql.Date[]) {
            jdbcType = Types.DATE;
        } else if (object instanceof java.sql.Clob[]) {
            jdbcType = Types.CLOB;
        } else if (object instanceof Calendar[]) {
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.TIMESTAMP).jdbcType;
            object = dialect.getTimestampFromCalendar((Calendar) object);
        } else if (object instanceof Integer[]) {
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.INTEGER).jdbcType;
        } else {/*from   w  w  w  .j  a v a  2 s .c o m*/
            jdbcType = dialect.getJDBCTypeAndString(ColumnType.CLOB).jdbcType;
        }
        Array array = dialect.createArrayOf(jdbcType, (Object[]) object, connection);
        ps.setArray(i, array);
    } else {
        ps.setObject(i, object);
    }
    return i;
}

From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java

/**
 * Insert a blob//  w  w  w  . j a  v  a 2s.  c o m
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public void insertLoopPrepStatement(Connection connection, int numberToInsert, File blobFile) throws Exception {

    // We can now use our Remote JDBC Connection as a regular Connection!
    connection.setAutoCommit(false);

    // We will do all our remote insert in a SQL Transaction
    try {

        String sql = "insert into orderlog values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";

        // Create a new Prepared Statement
        PreparedStatement prepStatement = null;

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + numberToInsert + " orderlog...");

        for (int customerId = 1; customerId < numberToInsert + 1; customerId++) {
            int i = 1;
            long theTime = new java.util.Date().getTime();

            // We will insert a Blob (the image of the product).
            // The transfer will be done in streaming both on the client
            // and on the Servlet Server: we can upload/download very big
            // files.

            InputStream in = null;
            OutputStream out = null;

            try {
                in = new FileInputStream(blobFile);
                Blob blob = connection.createBlob();
                out = blob.setBinaryStream(1);
                IOUtils.copy(in, out);

                prepStatement = connection.prepareStatement(sql);

                prepStatement.setInt(i++, customerId);
                prepStatement.setInt(i++, customerId);
                prepStatement.setString(i++, "Item Description No " + customerId);
                prepStatement.setBigDecimal(i++, new BigDecimal(customerId));
                prepStatement.setDate(i++, new java.sql.Date(theTime));
                prepStatement.setTimestamp(i++, new Timestamp(theTime));
                prepStatement.setBlob(i++, blob);

                SqlUtil sqlUtil = new SqlUtil(connection);
                if (sqlUtil.isIngres()) {
                    prepStatement.setInt(i++, 0);
                } else {
                    prepStatement.setBoolean(i++, false);
                }

                prepStatement.setInt(i++, customerId);

                // SystemOutHandle.display("Before executeUpdate...");
                prepStatement.executeUpdate();

                // Close and free are important to delete temp files
                prepStatement.close();
                blob.free();
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

        }

        // We do either everything in a single transaction or nothing
        connection.commit(); // Commit is propagated on Server
        MessageDisplayer.display("Remote Commit Done on AceQL Server!");
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(true);
    }

}

From source file:org.ojbc.adapters.analyticaldatastore.dao.AnalyticalDatastoreDAOImpl.java

@Override
public Integer saveIncident(final Incident inboundIncident) {
    log.debug("Inserting row into Incident table: " + inboundIncident.toString());

    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbcTemplate.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {

            String incidentInsertStatement = "";
            String[] insertArgs = null;

            if (inboundIncident.getIncidentID() == null) {
                incidentInsertStatement = "INSERT into INCIDENT (ReportingAgencyID, IncidentCaseNumber,"
                        + "IncidentLocationLatitude, IncidentLocationLongitude, IncidentLocationStreetAddress,IncidentLocationTown,IncidentDate,IncidentTime,ReportingSystem,RecordType) values (?,?,?,?,?,?,?,?,?,?)";

                insertArgs = new String[] { "ReportingAgencyID",
                        "IncidentCaseNumber" + "IncidentLocationLatitude", "IncidentLocationLongitude",
                        "IncidentLocationStreetAddress", "IncidentLocationTown", "IncidentDate", "IncidentTime",
                        "ReportingSystem", "RecordType" };
            } else {
                incidentInsertStatement = "INSERT into INCIDENT (ReportingAgencyID, IncidentCaseNumber,"
                        + "IncidentLocationLatitude, IncidentLocationLongitude, IncidentLocationStreetAddress,IncidentLocationTown,IncidentDate,IncidentTime,ReportingSystem,RecordType, IncidentID) values (?,?,?,?,?,?,?,?,?,?,?)";

                insertArgs = new String[] { "ReportingAgencyID",
                        "IncidentCaseNumber" + "IncidentLocationLatitude", "IncidentLocationLongitude",
                        "IncidentLocationStreetAddress", "IncidentLocationTown", "IncidentDate", "IncidentTime",
                        "ReportingSystem", "RecordType", "IncidentID" };
            }/*from  www.j  a  v a  2 s.  co  m*/

            PreparedStatement ps = connection.prepareStatement(incidentInsertStatement, insertArgs);
            if (inboundIncident.getReportingAgencyID() != null) {
                ps.setInt(1, inboundIncident.getReportingAgencyID());
            } else {
                ps.setNull(1, java.sql.Types.NULL);
            }

            ps.setString(2, inboundIncident.getIncidentCaseNumber());
            ps.setBigDecimal(3, inboundIncident.getIncidentLocationLatitude());
            ps.setBigDecimal(4, inboundIncident.getIncidentLocationLongitude());
            ps.setString(5, inboundIncident.getIncidentLocationStreetAddress());
            ps.setString(6, inboundIncident.getIncidentLocationTown());
            ps.setDate(7, new java.sql.Date(inboundIncident.getIncidentDate().getTime()));
            ps.setTime(8, new java.sql.Time(inboundIncident.getIncidentDate().getTime()));
            ps.setString(9, inboundIncident.getReportingSystem());
            ps.setString(10, String.valueOf(inboundIncident.getRecordType()));

            if (inboundIncident.getIncidentID() != null) {
                ps.setInt(11, inboundIncident.getIncidentID());
            }

            return ps;
        }
    }, keyHolder);

    Integer returnValue = null;

    if (inboundIncident.getIncidentID() != null) {
        returnValue = inboundIncident.getIncidentID();
    } else {
        returnValue = keyHolder.getKey().intValue();
    }

    return returnValue;
}

From source file:org.openmrs.util.databasechange.AddConceptMapTypesChangeset.java

/**
 * Executes all the changes to the concept names as a batch update.
 *
 * @param connection The database connection
 *//*from   w  w w  . j  av  a  2 s  .c om*/
private void runBatchInsert(JdbcConnection connection) throws CustomChangeException {
    PreparedStatement pStmt = null;
    ResultSet rs = null;
    try {
        connection.setAutoCommit(false);

        Integer userId = DatabaseUpdater.getAuthenticatedUserId();
        //if we have no authenticated user(for API users), set as Daemon
        if (userId == null || userId < 1) {
            userId = getInt(connection, "SELECT min(user_id) FROM users");
            //leave it as null rather than setting it to 0
            if (userId < 1) {
                userId = null;
            }
        }

        //userId is not a param, because it's easier this way if it's null
        pStmt = connection.prepareStatement("INSERT INTO concept_map_type "
                + "(concept_map_type_id, name, is_hidden, retired, creator, date_created, uuid) VALUES(?,?,?,?,"
                + userId + ",?,?)");

        int mapTypeId = 1;

        for (String map : visibleConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];

            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, false);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();

            mapTypeId++;
        }

        for (String map : hiddenConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];

            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, true);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();

            mapTypeId++;
        }

        try {
            int[] updateCounts = pStmt.executeBatch();
            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.debug("Successfully executed; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert");
                }
            }

            log.debug("Committing inserts...");
            connection.commit();
        } catch (BatchUpdateException be) {
            log.warn("Error generated while processsing batch insert", be);
            int[] updateCounts = be.getUpdateCounts();

            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.warn("Executed with exception: insertCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.warn("Executed with exception; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert with exception");
                }
            }

            try {
                log.debug("Rolling back batch", be);
                connection.rollback();
            } catch (Exception rbe) {
                log.warn("Error generated while rolling back batch insert", be);
            }

            //marks the changeset as a failed one
            throw new CustomChangeException("Failed to insert one or more concept map types", be);
        }
    } catch (DatabaseException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } catch (SQLException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } finally {
        //reset to auto commit mode
        try {
            connection.setAutoCommit(true);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }

        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

/**
 * Persist the passed in NCube//from  w w  w. j  a  va  2  s.  c  o  m
 *
 * @param connection JDBC connection
 * @param ncube      NCube to be persisted
 */
public static void createCube(Connection connection, String app, NCube ncube, String version) {
    validate(connection, app, version);
    if (ncube == null) {
        throw new IllegalArgumentException("NCube cannot be null when creating a new n-cube");
    }
    validateCubeName(ncube.getName());

    synchronized (cubeList) {
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(
                    "SELECT n_cube_id AS \"id\" FROM n_cube WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ?");
            stmt.setString(1, app);
            stmt.setString(2, ncube.getName());
            stmt.setString(3, version);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) { // NCube with same name and version number already exists.
                throw new IllegalStateException(
                        "NCube '" + ncube.getName() + "' (" + version + ") already exists.");
            } else { // Do INSERT
                stmt.close();
                stmt = connection.prepareStatement(
                        "INSERT INTO n_cube (n_cube_id, app_cd, n_cube_nm, cube_value_bin, version_no_cd, create_dt, sys_effective_dt) VALUES (?, ?, ?, ?, ?, ?, ?)");
                stmt.setLong(1, UniqueIdGenerator.getUniqueId());
                stmt.setString(2, app);
                stmt.setString(3, ncube.getName());
                String json = new JsonFormatter().format(ncube);
                //                    String json = JsonWriter.objectToJson(ncube);
                stmt.setBytes(4, json.getBytes("UTF-8"));
                stmt.setString(5, version);
                java.sql.Date now = new java.sql.Date(System.currentTimeMillis());
                stmt.setDate(6, now);
                stmt.setDate(7, now);
                int rowCount = stmt.executeUpdate();
                if (rowCount != 1) {
                    throw new IllegalStateException("error saving new NCube: " + ncube.getName() + "', app: "
                            + app + ", version: " + version + " (" + rowCount + " rows inserted, should be 1)");
                }
            }

            addCube(ncube, version);
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            String s = "Unable to save NCube: " + ncube.getName() + ", app: " + app + ", version: " + version
                    + " to database";
            LOG.error(s, e);
            throw new RuntimeException(s, e);
        } finally {
            jdbcCleanup(stmt);
        }
    }
}

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;//from   ww w .  ja va2 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.jobjects.dao.annotation.ManagerTools.java

protected final void setAll(PreparedStatement pstmt, int i, Object obj) throws SQLException {
    if (obj instanceof Boolean) {
        pstmt.setBoolean(i, ((Boolean) obj).booleanValue());
    }//www .j a va 2s  . co  m
    if (obj instanceof Byte) {
        pstmt.setByte(i, ((Byte) obj).byteValue());
    }
    if (obj instanceof Short) {
        pstmt.setShort(i, ((Short) obj).shortValue());
    }
    if (obj instanceof Integer) {
        pstmt.setInt(i, ((Integer) obj).intValue());
    }
    if (obj instanceof Long) {
        pstmt.setLong(i, ((Long) obj).longValue());
    }
    if (obj instanceof Float) {
        pstmt.setFloat(i, ((Float) obj).floatValue());
    }
    if (obj instanceof Double) {
        pstmt.setDouble(i, ((Double) obj).doubleValue());
    }
    if (obj instanceof Timestamp) {
        pstmt.setTimestamp(i, ((Timestamp) obj));
    }
    if (obj instanceof Date) {
        pstmt.setDate(i, ((Date) obj));
    }
    if (obj instanceof BigDecimal) {
        pstmt.setBigDecimal(i, ((BigDecimal) obj));
    }
    if (obj instanceof String) {
        pstmt.setString(i, ((String) obj));
    }
}

From source file:chh.utils.db.source.common.JdbcClient.java

private void setPreparedStatementParams(PreparedStatement preparedStatement, List<Column> columnList)
        throws SQLException {
    int index = 1;
    for (Column column : columnList) {
        Class columnJavaType = Util.getJavaType(column.getSqlType());
        if (column.getVal() == null) {
            preparedStatement.setNull(index, column.getSqlType());
        } else if (columnJavaType.equals(String.class)) {
            preparedStatement.setString(index, (String) column.getVal());
        } else if (columnJavaType.equals(Integer.class)) {
            preparedStatement.setInt(index, (Integer) column.getVal());
        } else if (columnJavaType.equals(Double.class)) {
            preparedStatement.setDouble(index, (Double) column.getVal());
        } else if (columnJavaType.equals(Float.class)) {
            preparedStatement.setFloat(index, (Float) column.getVal());
        } else if (columnJavaType.equals(Short.class)) {
            preparedStatement.setShort(index, (Short) column.getVal());
        } else if (columnJavaType.equals(Boolean.class)) {
            preparedStatement.setBoolean(index, (Boolean) column.getVal());
        } else if (columnJavaType.equals(byte[].class)) {
            preparedStatement.setBytes(index, (byte[]) column.getVal());
        } else if (columnJavaType.equals(Long.class)) {
            preparedStatement.setLong(index, (Long) column.getVal());
        } else if (columnJavaType.equals(Date.class)) {
            preparedStatement.setDate(index, (Date) column.getVal());
        } else if (columnJavaType.equals(Time.class)) {
            preparedStatement.setTime(index, (Time) column.getVal());
        } else if (columnJavaType.equals(Timestamp.class)) {
            preparedStatement.setTimestamp(index, (Timestamp) column.getVal());
        } else {/* w  w  w .ja va 2  s . c om*/
            throw new RuntimeException(
                    "Unknown type of value " + column.getVal() + " for column " + column.getColumnName());
        }
        ++index;
    }
}

From source file:org.apache.phoenix.query.BaseTest.java

protected static void initATableValues(String tenantId, byte[][] splits, Date date, Long ts, String url)
        throws Exception {
    if (ts == null) {
        ensureTableCreated(url, ATABLE_NAME, splits);
    } else {/*www . j  a va  2 s  .co  m*/
        ensureTableCreated(url, ATABLE_NAME, splits, ts - 5);
    }

    Properties props = new Properties();
    if (ts != null) {
        props.setProperty(CURRENT_SCN_ATTRIB, Long.toString(ts - 3));
    }
    Connection conn = DriverManager.getConnection(url, props);
    try {
        // Insert all rows at ts
        PreparedStatement stmt = conn.prepareStatement("upsert into " + "ATABLE(" + "    ORGANIZATION_ID, "
                + "    ENTITY_ID, " + "    A_STRING, " + "    B_STRING, " + "    A_INTEGER, " + "    A_DATE, "
                + "    X_DECIMAL, " + "    X_LONG, " + "    X_INTEGER," + "    Y_INTEGER," + "    A_BYTE,"
                + "    A_SHORT," + "    A_FLOAT," + "    A_DOUBLE," + "    A_UNSIGNED_FLOAT,"
                + "    A_UNSIGNED_DOUBLE)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        stmt.setString(1, tenantId);
        stmt.setString(2, ROW1);
        stmt.setString(3, A_VALUE);
        stmt.setString(4, B_VALUE);
        stmt.setInt(5, 1);
        stmt.setDate(6, date);
        stmt.setBigDecimal(7, null);
        stmt.setNull(8, Types.BIGINT);
        stmt.setNull(9, Types.INTEGER);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 1);
        stmt.setShort(12, (short) 128);
        stmt.setFloat(13, 0.01f);
        stmt.setDouble(14, 0.0001);
        stmt.setFloat(15, 0.01f);
        stmt.setDouble(16, 0.0001);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW2);
        stmt.setString(3, A_VALUE);
        stmt.setString(4, C_VALUE);
        stmt.setInt(5, 2);
        stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1));
        stmt.setBigDecimal(7, null);
        stmt.setNull(8, Types.BIGINT);
        stmt.setNull(9, Types.INTEGER);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 2);
        stmt.setShort(12, (short) 129);
        stmt.setFloat(13, 0.02f);
        stmt.setDouble(14, 0.0002);
        stmt.setFloat(15, 0.02f);
        stmt.setDouble(16, 0.0002);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW3);
        stmt.setString(3, A_VALUE);
        stmt.setString(4, E_VALUE);
        stmt.setInt(5, 3);
        stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2));
        stmt.setBigDecimal(7, null);
        stmt.setNull(8, Types.BIGINT);
        stmt.setNull(9, Types.INTEGER);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 3);
        stmt.setShort(12, (short) 130);
        stmt.setFloat(13, 0.03f);
        stmt.setDouble(14, 0.0003);
        stmt.setFloat(15, 0.03f);
        stmt.setDouble(16, 0.0003);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW4);
        stmt.setString(3, A_VALUE);
        stmt.setString(4, B_VALUE);
        stmt.setInt(5, 4);
        stmt.setDate(6, date == null ? null : date);
        stmt.setBigDecimal(7, null);
        stmt.setNull(8, Types.BIGINT);
        stmt.setNull(9, Types.INTEGER);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 4);
        stmt.setShort(12, (short) 131);
        stmt.setFloat(13, 0.04f);
        stmt.setDouble(14, 0.0004);
        stmt.setFloat(15, 0.04f);
        stmt.setDouble(16, 0.0004);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW5);
        stmt.setString(3, B_VALUE);
        stmt.setString(4, C_VALUE);
        stmt.setInt(5, 5);
        stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1));
        stmt.setBigDecimal(7, null);
        stmt.setNull(8, Types.BIGINT);
        stmt.setNull(9, Types.INTEGER);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 5);
        stmt.setShort(12, (short) 132);
        stmt.setFloat(13, 0.05f);
        stmt.setDouble(14, 0.0005);
        stmt.setFloat(15, 0.05f);
        stmt.setDouble(16, 0.0005);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW6);
        stmt.setString(3, B_VALUE);
        stmt.setString(4, E_VALUE);
        stmt.setInt(5, 6);
        stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2));
        stmt.setBigDecimal(7, null);
        stmt.setNull(8, Types.BIGINT);
        stmt.setNull(9, Types.INTEGER);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 6);
        stmt.setShort(12, (short) 133);
        stmt.setFloat(13, 0.06f);
        stmt.setDouble(14, 0.0006);
        stmt.setFloat(15, 0.06f);
        stmt.setDouble(16, 0.0006);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW7);
        stmt.setString(3, B_VALUE);
        stmt.setString(4, B_VALUE);
        stmt.setInt(5, 7);
        stmt.setDate(6, date == null ? null : date);
        stmt.setBigDecimal(7, BigDecimal.valueOf(0.1));
        stmt.setLong(8, 5L);
        stmt.setInt(9, 5);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 7);
        stmt.setShort(12, (short) 134);
        stmt.setFloat(13, 0.07f);
        stmt.setDouble(14, 0.0007);
        stmt.setFloat(15, 0.07f);
        stmt.setDouble(16, 0.0007);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW8);
        stmt.setString(3, B_VALUE);
        stmt.setString(4, C_VALUE);
        stmt.setInt(5, 8);
        stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1));
        stmt.setBigDecimal(7, BigDecimal.valueOf(3.9));
        long l = Integer.MIN_VALUE - 1L;
        assert (l < Integer.MIN_VALUE);
        stmt.setLong(8, l);
        stmt.setInt(9, 4);
        stmt.setNull(10, Types.INTEGER);
        stmt.setByte(11, (byte) 8);
        stmt.setShort(12, (short) 135);
        stmt.setFloat(13, 0.08f);
        stmt.setDouble(14, 0.0008);
        stmt.setFloat(15, 0.08f);
        stmt.setDouble(16, 0.0008);
        stmt.execute();

        stmt.setString(1, tenantId);
        stmt.setString(2, ROW9);
        stmt.setString(3, C_VALUE);
        stmt.setString(4, E_VALUE);
        stmt.setInt(5, 9);
        stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2));
        stmt.setBigDecimal(7, BigDecimal.valueOf(3.3));
        l = Integer.MAX_VALUE + 1L;
        assert (l > Integer.MAX_VALUE);
        stmt.setLong(8, l);
        stmt.setInt(9, 3);
        stmt.setInt(10, 300);
        stmt.setByte(11, (byte) 9);
        stmt.setShort(12, (short) 0);
        stmt.setFloat(13, 0.09f);
        stmt.setDouble(14, 0.0009);
        stmt.setFloat(15, 0.09f);
        stmt.setDouble(16, 0.0009);
        stmt.execute();

        conn.commit();
    } finally {
        conn.close();
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java

protected void applyParameters(PreparedStatement statement, ParameterValueList parameters)
        throws SQLException, SenderException {
    // statement.clearParameters();

    /*/*from  ww  w .  j  av  a 2 s  .  c o  m*/
          // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation.
          int senderParameterCount = parameters.size();
          int statementParameterCount = statement.getParameterMetaData().getParameterCount();
          if (statementParameterCount<senderParameterCount) {
             throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]");
          }
    */

    for (int i = 0; i < parameters.size(); i++) {
        ParameterValue pv = parameters.getParameterValue(i);
        String paramType = pv.getDefinition().getType();
        Object value = pv.getValue();
        //      log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]");

        if (Parameter.TYPE_DATE.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.DATE);
            } else {
                statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_DATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIME);
            } else {
                statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_NUMBER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.NUMERIC);
            } else {
                statement.setDouble(i + 1, ((Number) value).doubleValue());
            }
        } else if (Parameter.TYPE_INTEGER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.INTEGER);
            } else {
                statement.setInt(i + 1, (Integer) value);
            }
        } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
            if (value instanceof FileInputStream) {
                FileInputStream fis = (FileInputStream) value;
                long len = 0;
                try {
                    len = fis.getChannel().size();
                } catch (IOException e) {
                    log.warn(getLogPrefix() + "could not determine file size", e);
                }
                statement.setBinaryStream(i + 1, fis, (int) len);
            } else if (value instanceof ByteArrayInputStream) {
                ByteArrayInputStream bais = (ByteArrayInputStream) value;
                long len = bais.available();
                statement.setBinaryStream(i + 1, bais, (int) len);
            } else {
                throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                        + "] for parameter [" + pv.getDefinition().getName() + "]");
            }
        } else if ("string2bytes".equals(paramType)) {
            statement.setBytes(i + 1, ((String) value).getBytes());
        } else if ("bytes".equals(paramType)) {
            statement.setBytes(i + 1, (byte[]) value);
        } else {
            statement.setString(i + 1, (String) value);
        }
    }
}