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:br.com.fatecpg.repositories.mysql.MySqlLogRepository.java

@Override
public void add(Log log) {
    if (log == null) {
        throw new IllegalArgumentException("log can't be null.");
    }/*from w  ww. j  av  a2s  . c om*/

    String sql = "insert into log (applicationName, message, url, ipaddress, username, createdon, details) values (?, ?, ?, ?, ?, ?, ?)";
    Connection connection = dbProvider.getConnection();

    try {

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, log.getApplicationName());
        preparedStatement.setString(2, log.getMessage());
        preparedStatement.setString(3, log.getUrl());
        preparedStatement.setString(4, log.getIpAddress());
        preparedStatement.setString(5, log.getUsername());

        Date sqlDate = new Date(log.getCreatedDate().getYear(), log.getCreatedDate().getMonth(),
                log.getCreatedDate().getDay());

        preparedStatement.setDate(6, sqlDate);
        preparedStatement.setString(7, log.getDetails());

        preparedStatement.execute();

    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.kuali.kfs.gl.batch.dataaccess.impl.LedgerPreparedStatementCachingDaoJdbc.java

public void insertReversal(final Reversal reversal) {
    new InsertingJdbcWrapper<Reversal>() {
        @Override/*from  www  .j ava2s  .  c o m*/
        protected void populateStatement(PreparedStatement preparedStatement) throws SQLException {
            preparedStatement.setDate(1, reversal.getFinancialDocumentReversalDate());
            preparedStatement.setInt(2, reversal.getUniversityFiscalYear());
            preparedStatement.setString(3, reversal.getChartOfAccountsCode());
            preparedStatement.setString(4, reversal.getAccountNumber());
            preparedStatement.setString(5, reversal.getSubAccountNumber());
            preparedStatement.setString(6, reversal.getFinancialObjectCode());
            preparedStatement.setString(7, reversal.getFinancialSubObjectCode());
            preparedStatement.setString(8, reversal.getFinancialBalanceTypeCode());
            preparedStatement.setString(9, reversal.getFinancialObjectTypeCode());
            preparedStatement.setString(10, reversal.getUniversityFiscalPeriodCode());
            preparedStatement.setString(11, reversal.getFinancialDocumentTypeCode());
            preparedStatement.setString(12, reversal.getFinancialSystemOriginationCode());
            preparedStatement.setString(13, reversal.getDocumentNumber());
            preparedStatement.setInt(14, reversal.getTransactionLedgerEntrySequenceNumber());
            preparedStatement.setString(15, reversal.getTransactionLedgerEntryDescription());
            preparedStatement.setBigDecimal(16, reversal.getTransactionLedgerEntryAmount().bigDecimalValue());
            preparedStatement.setString(17, reversal.getTransactionDebitCreditCode());
            preparedStatement.setDate(18, reversal.getTransactionDate());
            preparedStatement.setString(19, reversal.getOrganizationDocumentNumber());
            preparedStatement.setString(20, reversal.getProjectCode());
            preparedStatement.setString(21, reversal.getOrganizationReferenceId());
            preparedStatement.setString(22, reversal.getReferenceFinancialDocumentTypeCode());
            preparedStatement.setString(23, reversal.getReferenceFinancialSystemOriginationCode());
            preparedStatement.setString(24, reversal.getReferenceFinancialDocumentNumber());
            preparedStatement.setString(25, reversal.getTransactionEncumbranceUpdateCode());
            preparedStatement.setDate(26, reversal.getTransactionPostingDate());
        }
    }.execute(Reversal.class);
}

From source file:org.gbif.harvest.portal.synchronise.dao.jdbc.AgentDaoImpl.java

/**
 * @see org.gbif.portal.dao.AgentDAO#create(org.gbif.portal.model.Agent)
 *//*from  w  ww  .  j a v a  2s. c  o  m*/
public long create(final Agent agent) {
    Date now = new Date();
    agent.setModified(now);
    agent.setCreated(now);

    KeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
            PreparedStatement ps = conn.prepareStatement(AgentDaoImpl.CREATE_SQL);
            ps.setString(1, StringUtils.trimToNull(agent.getName()));
            ps.setString(2, StringUtils.trimToNull(agent.getAddress()));
            ps.setString(3, StringUtils.trimToNull(agent.getEmail()));
            ps.setString(4, StringUtils.trimToNull(agent.getTelephone()));
            ps.setDate(5, createSQLDate(agent.getCreated()));
            ps.setDate(6, createSQLDate(agent.getModified()));
            return ps;
        }
    }, keyHolder);
    agent.setId(keyHolder.getKey().longValue());
    return keyHolder.getKey().longValue();
}

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

/**
 * Get the notes associated to an NCube//from w  w  w.j a  va 2s .c  om
 *
 * @return String notes.
 */
public static String getNotes(Connection connection, String app, String name, String version, Date sysDate) {
    validate(connection, app, version);
    validateCubeName(name);

    if (sysDate == null) {
        sysDate = new Date();
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT notes_bin FROM n_cube WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?)");
        stmt.setString(1, app);
        stmt.setString(2, name);
        stmt.setString(3, version);
        stmt.setDate(4, systemDate);
        stmt.setDate(5, systemDate);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            byte[] notes = rs.getBytes("notes_bin");
            return new String(notes == null ? "".getBytes() : notes, "UTF-8");
        }
        throw new IllegalArgumentException("No NCube matching passed in parameters.");
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        String s = "Unable to fetch notes for NCube: " + name + ", app: " + app + ", version: " + version;
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

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

/**
 * Get the Test Data associated to the NCube.
 *
 * @return String serialized JSON test data.  Use JsonReader to turn it back into
 * Java objects.//  ww w. j  a v a 2  s .  co  m
 */
public static String getTestData(Connection connection, String app, String name, String version, Date sysDate) {
    validate(connection, app, version);
    validateCubeName(name);

    if (sysDate == null) {
        sysDate = new Date();
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT test_data_bin FROM n_cube WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?)");
        stmt.setString(1, app);
        stmt.setString(2, name);
        stmt.setString(3, version);
        stmt.setDate(4, systemDate);
        stmt.setDate(5, systemDate);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            byte[] testData = rs.getBytes("test_data_bin");
            return new String(testData == null ? "".getBytes() : testData, "UTF-8");
        }
        throw new IllegalArgumentException("No NCube matching passed in parameters.");
    } catch (IllegalArgumentException e) {
        throw e;
    } catch (Exception e) {
        String s = "Unable to fetch test data for NCube: " + name + ", app: " + app + ", version: " + version;
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

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

/**
 * Retrieve all cube names that are deeply referenced by the named app, cube (name), version, and status.
 *///w w  w. ja  v a  2 s  .c o  m
public static void getReferencedCubeNames(Connection connection, String app, String name, String version,
        String status, Date sysDate, Set<String> refs) {
    validate(connection, app, version);
    validateCubeName(name);
    validateStatus(status);

    if (sysDate == null) {
        sysDate = new Date();
    }
    if (refs == null) {
        throw new IllegalArgumentException("null passed in for Set to hold referenced n-cube names");
    }

    PreparedStatement stmt = null;
    try {
        java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
        stmt = connection.prepareStatement(
                "SELECT cube_value_bin FROM n_cube WHERE n_cube_nm = ? AND app_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?) AND version_no_cd = ? AND status_cd = ?");

        stmt.setString(1, name);
        stmt.setString(2, app);
        stmt.setDate(3, systemDate);
        stmt.setDate(4, systemDate);
        stmt.setString(5, version);
        stmt.setString(6, status);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            byte[] jsonBytes = rs.getBytes("cube_value_bin");
            String json = new String(jsonBytes, "UTF-8");
            NCube ncube = ncubeFromJson(json);

            if (rs.next()) {
                throw new IllegalStateException(
                        "More than one NCube matching name: " + ncube.getName() + ", app: " + app
                                + ", version: " + version + ", status: " + status + ", sysDate: " + sysDate);
            }

            Set<String> subCubeList = ncube.getReferencedCubeNames();
            refs.addAll(subCubeList);

            for (String cubeName : subCubeList) {
                if (!refs.contains(cubeName)) {
                    getReferencedCubeNames(connection, app, cubeName, version, status, sysDate, refs);
                }
            }
        }
    } catch (IllegalStateException e) {
        throw e;
    } catch (Exception e) {
        String s = "Unable to load nNCube: " + name + ", app: " + app + ", version: " + version + ", status: "
                + status + ", sysDate: " + sysDate + " from database";
        LOG.error(s, e);
        throw new RuntimeException(s, e);
    } finally {
        jdbcCleanup(stmt);
    }
}

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

/**
 * Load an NCube from the database (any joined sub-cubes will also be loaded).
 *
 * @return NCube that matches, or null if not found.
 *//*from   ww w  . j a v a 2 s  . c  o m*/
public static boolean doesCubeExist(Connection connection, String app, String name, String version,
        String status, Date sysDate) {
    validate(connection, app, version);
    validateCubeName(name);
    validateStatus(status);

    if (sysDate == null) {
        sysDate = new Date();
    }

    synchronized (cubeList) {
        PreparedStatement stmt = null;
        try {
            java.sql.Date systemDate = new java.sql.Date(sysDate.getTime());
            stmt = connection.prepareStatement(
                    "SELECT n_cube_nm FROM n_cube WHERE n_cube_nm = ? AND app_cd = ? AND sys_effective_dt <= ? AND (sys_expiration_dt IS NULL OR sys_expiration_dt >= ?) AND version_no_cd = ? AND status_cd = ?");

            stmt.setString(1, name);
            stmt.setString(2, app);
            stmt.setDate(3, systemDate);
            stmt.setDate(4, systemDate);
            stmt.setString(5, version);
            stmt.setString(6, status);
            ResultSet rs = stmt.executeQuery();

            return rs.next();
        } catch (Exception e) {
            String s = "Error finding cube: " + name + ", app: " + app + ", version: " + version + ", status: "
                    + status + ", sysDate: " + sysDate + " from database";
            LOG.error(s, e);
            throw new RuntimeException(s, e);
        } finally {
            jdbcCleanup(stmt);
        }
    }
}

From source file:org.gbif.harvest.portal.synchronise.dao.jdbc.AgentDaoImpl.java

/**
 * @see org.gbif.portal.dao.AgentDAO#updateOrCreate(org.gbif.portal.model.Agent)
 */// w w w .  j  a va  2 s  . c  om
public long updateOrCreate(final Agent agent) {
    if (agent.getId() <= 0) {
        return create(agent);
    } else {
        Date now = new Date();
        agent.setModified(now);
        getJdbcTemplate().update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                PreparedStatement ps = conn.prepareStatement(AgentDaoImpl.UPDATE_SQL);
                ps.setString(1, StringUtils.trimToNull(agent.getName()));
                ps.setString(2, StringUtils.trimToNull(agent.getAddress()));
                ps.setString(3, StringUtils.trimToNull(agent.getEmail()));
                ps.setString(4, StringUtils.trimToNull(agent.getTelephone()));
                ps.setDate(5, createSQLDate(agent.getModified()));
                ps.setLong(6, agent.getId());
                return ps;
            }
        });
        return agent.getId();
    }
}

From source file:org.castor.jdo.engine.SQLTypeInfos.java

/**
 * Set given value on given PreparedStatement at given index with given SQL type.
 * //  ww  w  . j  av  a  2 s.co m
 * @param stmt The PreparedStatement to set value on.
 * @param index The index of the value in the PreparedStatement.
 * @param value The value to set.
 * @param sqlType The SQL type of the value.
 */
public static void setValue(final PreparedStatement stmt, final int index, final Object value,
        final int sqlType) {
    try {
        if (value == null) {
            stmt.setNull(index, sqlType);
        } else {
            // Special processing for BLOB and CLOB types, because they are mapped
            // by Castor to java.io.InputStream and java.io.Reader, respectively,
            // while JDBC driver expects java.sql.Blob and java.sql.Clob.
            switch (sqlType) {
            case Types.FLOAT:
            case Types.DOUBLE:
                stmt.setDouble(index, ((Double) value).doubleValue());
                break;
            case Types.REAL:
                stmt.setFloat(index, ((Float) value).floatValue());
                break;
            case Types.TIME:
                final Time time = value instanceof java.util.Date ? new Time(((java.util.Date) value).getTime())
                        : null;
                stmt.setTime(index, time != null ? time : (Time) value, getCalendar());
                break;
            case Types.DATE:
                final Date date = value instanceof java.util.Date ? new Date(((java.util.Date) value).getTime())
                        : null;
                stmt.setDate(index, date != null ? date : (Date) value);
                break;
            case Types.TIMESTAMP:
                final Timestamp timestamp = value instanceof java.util.Date
                        ? new Timestamp(((java.util.Date) value).getTime())
                        : null;
                stmt.setTimestamp(index, timestamp != null ? timestamp : (Timestamp) value, getCalendar());
                break;
            case Types.BLOB:
                try {
                    InputStream stream;
                    if (value instanceof byte[]) {
                        stream = new ByteArrayInputStream((byte[]) value);
                    } else {
                        stream = (InputStream) value;
                    }
                    stmt.setBinaryStream(index, stream, stream.available());
                } catch (IOException ex) {
                    throw new SQLException(ex.toString());
                }
                break;
            case Types.CLOB:
                if (value instanceof String) {
                    stmt.setCharacterStream(index, new StringReader((String) value),
                            Math.min(((String) value).length(), Integer.MAX_VALUE));
                } else {
                    stmt.setCharacterStream(index, ((Clob) value).getCharacterStream(),
                            (int) Math.min(((Clob) value).length(), Integer.MAX_VALUE));
                }
                break;
            default:
                stmt.setObject(index, value, sqlType);
                break;
            }
        }
    } catch (SQLException ex) {
        LOG.error("Unexpected SQL exception: ", ex);
    }
}

From source file:com.stratelia.webactiv.util.DBUtil.java

/**
 * Centralization in order to sets the parameters on a prepare statement.
 * @param preparedStatement//from  w  w  w . jav a2s . com
 * @param parameters
 * @throws SQLException
 */
public static <O> void setParameters(PreparedStatement preparedStatement, Collection<O> parameters)
        throws SQLException {
    int paramIndex = 1;
    for (Object parameter : parameters) {
        if (parameter == null) {
            preparedStatement.setObject(paramIndex, null);
        } else if (parameter instanceof String) {
            preparedStatement.setString(paramIndex, (String) parameter);
        } else if (parameter instanceof Enum) {
            preparedStatement.setString(paramIndex, ((Enum) parameter).name());
        } else if (parameter instanceof Integer) {
            preparedStatement.setInt(paramIndex, (Integer) parameter);
        } else if (parameter instanceof Long) {
            preparedStatement.setLong(paramIndex, (Long) parameter);
        } else if (parameter instanceof Timestamp) {
            preparedStatement.setTimestamp(paramIndex, (Timestamp) parameter);
        } else if (parameter instanceof Date) {
            preparedStatement.setDate(paramIndex, new java.sql.Date(((Date) parameter).getTime()));
        } else if (parameter instanceof UserDetail) {
            preparedStatement.setString(paramIndex, ((UserDetail) parameter).getId());
        } else {
            throw new IllegalArgumentException("SQL parameter type not handled: " + parameter.getClass());
        }
        paramIndex++;
    }
}