List of usage examples for java.sql PreparedStatement setTimestamp
void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException;
java.sql.Timestamp
value. From source file:net.bhira.sample.api.dao.EmployeeDaoImpl.java
/** * @see net.bhira.sample.api.dao.EmployeeDao#save(net.bhira.sample.model.Employee) *//* w ww.j av a2 s . c o m*/ @Override public void save(Employee employee) throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException { try { if (employee == null) { throw new InvalidObjectException("Employee object is null."); } employee.initForSave(); employee.validate(); boolean isNew = employee.isNew(); int count = 0; if (isNew) { // for new employee, construct SQL insert statement KeyHolder keyHolder = new GeneratedKeyHolder(); count = jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); pstmt.setLong(1, employee.getCompanyId()); if (employee.getDepartmentId() == 0) { pstmt.setNull(2, java.sql.Types.BIGINT); } else { pstmt.setLong(2, employee.getDepartmentId()); } pstmt.setString(3, employee.getName()); if (employee.getManagerId() == 0) { pstmt.setNull(4, java.sql.Types.BIGINT); } else { pstmt.setLong(4, employee.getManagerId()); } pstmt.setString(5, employee.getSalutation()); pstmt.setString(6, employee.getSex() == null ? null : employee.getSex().toString()); pstmt.setDate(7, employee.getDOB() == null ? null : new Date(employee.getDOB().getTime())); pstmt.setString(8, employee.getTitle()); pstmt.setString(9, employee.getAddress()); pstmt.setTimestamp(10, new Timestamp(employee.getCreated().getTime())); pstmt.setTimestamp(11, new Timestamp(employee.getModified().getTime())); pstmt.setString(12, employee.getCreatedBy()); pstmt.setString(13, employee.getModifiedBy()); return pstmt; } }, keyHolder); // fetch the newly created auto-increment ID employee.setId(keyHolder.getKey().longValue()); LOG.debug("inserted employee, count = {}, id = {}", count, employee.getId()); } else { // for existing employee, construct SQL update statement Long deptId = employee.getDepartmentId() == 0 ? null : employee.getDepartmentId(); Long mgrId = employee.getManagerId() == 0 ? null : employee.getManagerId(); String sex = employee.getSex() == null ? null : employee.getSex().toString(); Date dob = employee.getDOB() == null ? null : new Date(employee.getDOB().getTime()); Object[] args = new Object[] { employee.getCompanyId(), deptId, employee.getName(), mgrId, employee.getSalutation(), sex, dob, employee.getTitle(), employee.getAddress(), employee.getModified(), employee.getModifiedBy(), employee.getId() }; count = jdbcTemplate.update(SQL_UPDATE, args); LOG.debug("updated employee, count = {}, id = {}", count, employee.getId()); } // if insert/update has 0 count value, then rollback if (count <= 0) { throw new ObjectNotFoundException("Employee with ID " + employee.getId() + " was not found."); } // update dependent entries, as needed if (isNew) { // for new model if there is contact info, save it to contact info table and then // add entry in relationship table if (employee.getContactInfo() != null) { contactInfoDao.save(employee.getContactInfo()); Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } else { // for existing model, fetch contact info ID from relationship table List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class, new Object[] { employee.getId() }); Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null; if (employee.getContactInfo() == null) { // clean up old contact info entry, if needed if (cinfoId != null) { jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { employee.getId() }); contactInfoDao.delete(cinfoId); } } else { // insert/update contact info entry if (cinfoId != null) { employee.getContactInfo().setId(cinfoId); contactInfoDao.save(employee.getContactInfo()); } else { contactInfoDao.save(employee.getContactInfo()); Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } } } catch (DataIntegrityViolationException dive) { String msg = dive.getMessage(); if (msg != null) { if (msg.contains("fk_employee_compy")) { throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive); } else if (msg.contains("fk_employee_dept")) { throw new InvalidReferenceException("Invalid reference for attribute 'departmentId'", dive); } else if (msg.contains("fk_employee_mgr")) { throw new InvalidReferenceException("Invalid reference for attribute 'managerId'", dive); } } throw dive; } }
From source file:de.anycook.db.mysql.DBGetRecipe.java
public List<Recipe> getAllRecipes(int loginId, Date lastModified) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement( "SELECT versions.id AS id, gerichte.name AS name, beschreibung, " + "IFNULL(versions.imagename, " + "CONCAT('category/', kategorien.image)) AS image, gerichte.eingefuegt AS created, " + "min, std, skill, kalorien, personen, kategorien_name, " + "active_id, users_id, users.image, nickname, viewed, last_change, " + "(SELECT COUNT(users_id) FROM schmeckt " + "WHERE schmeckt.gerichte_name = gerichte.name AND schmeckt.users_id = ?) AS tastes " + "FROM gerichte " + "INNER JOIN versions ON IF(active_id > 0, gerichte.name = gerichte_name " + "AND active_id = versions.id, gerichte.name = gerichte_name) " + "INNER JOIN users ON users_id = users.id " + "INNER JOIN kategorien ON kategorien_name = kategorien.name " + "WHERE last_change > ? " + "GROUP BY name;"); preparedStatement.setInt(1, loginId); preparedStatement.setTimestamp(2, new Timestamp(lastModified.getTime())); ResultSet data = preparedStatement.executeQuery(); return getRecipes(data); }
From source file:com.commander4j.db.JDBDespatch.java
public boolean update() { boolean result = false; logger.debug("update [" + getDespatchNo() + "]"); if (isValid(false) == true) { try {//from ww w . ja v a 2s. c o m PreparedStatement stmtupdate; stmtupdate = Common.hostList.getHost(getHostID()).getConnection(getSessionID()).prepareStatement( Common.hostList.getHost(getHostID()).getSqlstatements().getSQL("JDBDespatch.update")); stmtupdate.setTimestamp(1, getDespatchDate()); stmtupdate.setString(2, getLocationIDFrom()); stmtupdate.setString(3, getStatus()); stmtupdate.setString(4, getTrailer()); stmtupdate.setString(5, getHaulier()); stmtupdate.setInt(6, getTotalPallets()); stmtupdate.setString(7, getLocationIDTo()); stmtupdate.setLong(8, getTransactionRef()); stmtupdate.setString(9, getLoadNo()); stmtupdate.setString(10, getJourneyRef()); stmtupdate.setString(11, getDespatchNo()); stmtupdate.execute(); stmtupdate.clearParameters(); Common.hostList.getHost(getHostID()).getConnection(getSessionID()).commit(); stmtupdate.close(); if (getJourneyRef().equals(getJourneyRefOLD()) == false) { if (journey.getJourneyRefProperties(getJourneyRefOLD())) { if (getJourneyRefOLD().equals("") == false) { journey.setDespatchNo(""); journey.setStatus("Unassigned"); journey.update(); } } if (journey.getJourneyRefProperties(getJourneyRef())) { if (getJourneyRef().equals("") == false) { journey.setDespatchNo(getDespatchNo()); journey.setStatus("Assigned"); journey.update(); } } setJourneyRefOLD(getJourneyRef()); } result = true; } catch (SQLException e) { setErrorMessage(e.getMessage()); } } return result; }
From source file:com.liferay.portal.upgrade.util.Table.java
public void setColumn(PreparedStatement ps, int index, Integer type, String value) throws Exception { int t = type.intValue(); int paramIndex = index + 1; if (t == Types.BIGINT) { ps.setLong(paramIndex, GetterUtil.getLong(value)); } else if (t == Types.BOOLEAN) { ps.setBoolean(paramIndex, GetterUtil.getBoolean(value)); } else if ((t == Types.CLOB) || (t == Types.VARCHAR)) { value = StringUtil.replace(value, SAFE_CHARS[1], SAFE_CHARS[0]); ps.setString(paramIndex, value); } else if (t == Types.DOUBLE) { ps.setDouble(paramIndex, GetterUtil.getDouble(value)); } else if (t == Types.FLOAT) { ps.setFloat(paramIndex, GetterUtil.getFloat(value)); } else if (t == Types.INTEGER) { ps.setInt(paramIndex, GetterUtil.getInteger(value)); } else if (t == Types.SMALLINT) { ps.setShort(paramIndex, GetterUtil.getShort(value)); } else if (t == Types.TIMESTAMP) { if (StringPool.NULL.equals(value)) { ps.setTimestamp(paramIndex, null); } else {/*from w w w . j a v a 2 s.c o m*/ DateFormat df = DateUtil.getISOFormat(); ps.setTimestamp(paramIndex, new Timestamp(df.parse(value).getTime())); } } else { throw new UpgradeException("Upgrade code using unsupported class type " + type); } }
From source file:gov.nih.nci.cabig.caaers.datamigrator.UserDataMigrator.java
/** * This method inserts appropriate records into study personnel table based on existing role_code. * @param map/*from ww w.jav a 2 s .co m*/ * @param groups */ @SuppressWarnings("unchecked") protected void insertIntoStudyPersonnel(final Map map, final List groups, final boolean onOracleDB) { String sql = getInsertStudyPersonnelSql(onOracleDB); BatchPreparedStatementSetter setter = null; setter = new BatchPreparedStatementSetter() { public int getBatchSize() { return groups.size(); } public void setValues(PreparedStatement ps, int index) throws SQLException { java.sql.Timestamp startDate = (java.sql.Timestamp) map.get("start_date"); java.sql.Timestamp endDate = (java.sql.Timestamp) map.get("end_date"); if (onOracleDB) { BigDecimal studySiteId = (BigDecimal) map.get("study_sites_id"); ps.setBigDecimal(1, studySiteId); } else { int studySiteId = ((Integer) map.get("study_sites_id")).intValue(); ps.setInt(1, studySiteId); } ps.setString(2, groups.get(index).toString()); if (onOracleDB) { BigDecimal retiredIndicator = (BigDecimal) map.get("retired_indicator"); ps.setBigDecimal(3, retiredIndicator); } else { Boolean retiredIndicator = (Boolean) map.get("retired_indicator"); ps.setBoolean(3, retiredIndicator); } ps.setTimestamp(4, startDate); ps.setTimestamp(5, endDate); if (onOracleDB) { BigDecimal siteResearchStaffId = (BigDecimal) map.get("site_research_staffs_id"); ps.setBigDecimal(6, siteResearchStaffId); } else { int siteResearchStaffId = ((Integer) map.get("site_research_staffs_id")).intValue(); ps.setInt(6, siteResearchStaffId); } } }; getJdbcTemplate().batchUpdate(sql, setter); }
From source file:com.skycloud.management.portal.admin.sysmanage.dao.impl.UserManageDaoImpl.java
@Override public int saveCompany(final TCompanyInfo tcompanyinfo) throws SQLException { KeyHolder keyHolder = new GeneratedKeyHolder(); final String sql = "insert into T_SCS_COMPANY_INFO (COMP_LEGAL_PERSON,COMP_CN_NAME," + "COMP_LEGAL_PERSON_ID," + " COMP_ADDRESS,POST_CODE," + " COMP_PHONE,RELA_MOBILE,COMP_FAX,COMP_EMAIL," + " COMP_ORG_CODE,BUS_LICENSE_NUM, " + " COMP_BANK_NAME,COMP_BANK_ACCOUNT,FIR_CHECK_COMMENT,CHECK_STATE,BLN_START_TIME,BLN_END_TIME) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,4,?,?);"; try {/* ww w. j av a 2 s. c o m*/ this.getJdbcTemplate().update(new PreparedStatementCreator() { int i = 1; @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); ps.setString(i++, tcompanyinfo.getCompLegalPerson()); ps.setString(i++, tcompanyinfo.getCompCnName()); ps.setString(i++, tcompanyinfo.getCompLegalPersonId()); ps.setString(i++, tcompanyinfo.getCompAddress()); ps.setString(i++, tcompanyinfo.getPostCode()); ps.setString(i++, tcompanyinfo.getCompPhone()); ps.setString(i++, tcompanyinfo.getRelaMobile()); ps.setString(i++, tcompanyinfo.getCompFax()); ps.setString(i++, tcompanyinfo.getCompEmail()); ps.setString(i++, tcompanyinfo.getCompOrgCode()); ps.setString(i++, tcompanyinfo.getBusLicenseNum()); ps.setString(i++, tcompanyinfo.getCompBankName()); ps.setString(i++, tcompanyinfo.getCompBankAccount()); ps.setString(i++, tcompanyinfo.getFirCheckComment()); ps.setTimestamp(i++, new Timestamp(new Date(System.currentTimeMillis()).getTime())); ps.setTimestamp(i++, new Timestamp(new Date(System.currentTimeMillis()).getTime())); return ps; } }, keyHolder); } catch (Exception e) { e.printStackTrace(); throw new SQLException("?"); } return keyHolder.getKey().intValue(); }
From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java
/** * Remove all expired tgts./*from ww w . j a v a 2 s. com*/ * * e.g. <code>DELETE FROM tgt WHERE expiration <= NOW()</code> * @see ICleanable#removeExpired() */ public void removeExpired() throws PersistenceException { Connection oConnection = null; PreparedStatement psSelect = null; PreparedStatement psDelete = null; ResultSet rsSelect = null; try { oConnection = _oDataSource.getConnection(); psSelect = oConnection.prepareStatement(_sSelectExpiredQuery); psSelect.setTimestamp(1, new Timestamp(System.currentTimeMillis())); rsSelect = psSelect.executeQuery(); while (rsSelect.next()) { String sId = rsSelect.getString(_sColumnID); if (sId != null) { try { ITGT tgt = retrieve(sId); if (tgt != null) { String sTGTUserID = null; String sTGTUserOrganization = null; IUser tgtUser = tgt.getUser(); if (tgtUser != null) { sTGTUserID = tgtUser.getID(); sTGTUserOrganization = tgtUser.getOrganization(); } else _logger.debug("No user available for TGT with ID: " + sId); _eventLogger.info(new UserEventLogItem(null, sId, null, UserEvent.TGT_EXPIRED, sTGTUserID, sTGTUserOrganization, null, null, this, "clean")); processEvent(TGTListenerEvent.ON_EXPIRE, tgt); } else _logger.debug("No TGT available with ID: " + sId); } catch (PersistenceException e) { _logger.debug("Invalid TGT will be removed: " + sId, e); } } } psDelete = oConnection.prepareStatement(_sRemoveExpiredQuery); psDelete.setTimestamp(1, new Timestamp(System.currentTimeMillis())); int i = psDelete.executeUpdate(); if (i > 0) _logger.debug(i + " TGT(s) expired"); int iCountR = 0; if (_aliasStoreSP != null) iCountR = _aliasStoreSP.clean(oConnection); int iCountF = 0; if (_aliasStoreIDP != null) iCountF = _aliasStoreIDP.clean(oConnection); if (_logger.isDebugEnabled() && iCountR + iCountF > 0) { StringBuffer sbDebug = new StringBuffer("Cleaned '"); sbDebug.append(iCountR); sbDebug.append("' (requestor based) aliasses and '"); sbDebug.append(iCountF); sbDebug.append("' (remote enitity based) aliasses"); _logger.debug(sbDebug.toString()); } } catch (SQLException e) { _logger.error("Could not execute delete expired", e); throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE); } catch (Exception e) { _logger.error("Internal error during removal of expired tgt", e); throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE); } finally { try { if (rsSelect != null) rsSelect.close(); } catch (SQLException e) { _logger.debug("Could not close resultset", e); } try { if (psSelect != null) psSelect.close(); } catch (SQLException e) { _logger.debug("Could not close select statement", e); } try { if (psDelete != null) psDelete.close(); } catch (SQLException e) { _logger.debug("Could not close delete statement", e); } try { if (oConnection != null) oConnection.close(); } catch (SQLException e) { _logger.debug("Could not close connection", e); } } }
From source file:edu.jhuapl.openessence.datasource.jdbc.JdbcOeDataSource.java
protected void setArguments(List<Object> arguments, PreparedStatement pStmt) throws SQLException { int argCount = 1; for (Object o : arguments) { // TODO NEED TO ADDRESS THE USE CASES FOR THIS null...POKUAM1...what if not nullable column? if (o == null) { pStmt.setObject(argCount, null); } else if (o instanceof java.sql.Timestamp) { pStmt.setTimestamp(argCount, (java.sql.Timestamp) o); } else if (o instanceof java.util.Date) { pStmt.setTimestamp(argCount, new java.sql.Timestamp(((java.util.Date) o).getTime())); } else if (o instanceof Integer) { pStmt.setInt(argCount, (Integer) o); } else if (o instanceof Long) { pStmt.setLong(argCount, (Long) o); } else if (o instanceof Float) { pStmt.setFloat(argCount, (Float) o); } else if (o instanceof Double) { pStmt.setDouble(argCount, (Double) o); } else if (o instanceof String) { pStmt.setString(argCount, (String) o); } else if (o instanceof Boolean) { pStmt.setBoolean(argCount, (Boolean) o); } else {//from w w w . ja va 2 s .c om throw new AssertionError("Unexpected object " + o + " " + o.getClass()); } argCount += 1; } }
From source file:se.technipelago.weather.chart.Generator.java
private float getValue(Date from, Date to, String column, int func) { PreparedStatement stmt = null; ResultSet result = null;//from w w w. j a v a 2s. c o m String f; float value = 0f; switch (func) { case MIN: f = "MIN"; break; case MAX: f = "MAX"; break; case SUM: f = "SUM"; break; case AVG: f = "AVG"; break; default: throw new IllegalArgumentException("Illegal function: " + func); } init(); try { stmt = conn.prepareStatement("SELECT " + f + "(" + column + ") FROM archive WHERE ts BETWEEN ? AND ?"); stmt.setTimestamp(1, new java.sql.Timestamp(from.getTime())); stmt.setTimestamp(2, new java.sql.Timestamp(to.getTime())); result = stmt.executeQuery(); if (result.next()) { value = result.getFloat(1); } } catch (SQLException ex) { Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex); } finally { if (result != null) { try { result.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close ResultSet", ex); } } if (stmt != null) { try { stmt.close(); } catch (SQLException ex) { log.log(Level.WARNING, "Failed to close select statement", ex); } } } return value; }
From source file:org.dcache.chimera.FsSqlDriver.java
private PreparedStatement generateAttributeUpdateStatement(Connection dbConnection, FsInode inode, Stat stat, int level) throws SQLException { final String attrUpdatePrefix = (level == 0) ? "UPDATE t_inodes SET ictime=?,igeneration=igeneration+1" : ("UPDATE t_level_" + level + " SET ictime=?"); final String attrUpdateSuffix = (level == 0 && stat.isDefined(Stat.StatAttributes.SIZE)) ? " WHERE inumber=? AND itype = " + UnixPermission.S_IFREG : " WHERE inumber=?"; StringBuilder sb = new StringBuilder(128); long ctime = stat.isDefined(Stat.StatAttributes.CTIME) ? stat.getCTime() : System.currentTimeMillis(); // set size always must trigger mtime update if (stat.isDefined(Stat.StatAttributes.SIZE) && !stat.isDefined(Stat.StatAttributes.MTIME)) { stat.setMTime(ctime);/* www . j av a 2 s . co m*/ } sb.append(attrUpdatePrefix); if (stat.isDefined(Stat.StatAttributes.UID)) { sb.append(",iuid=?"); } if (stat.isDefined(Stat.StatAttributes.GID)) { sb.append(",igid=?"); } if (stat.isDefined(Stat.StatAttributes.SIZE)) { sb.append(",isize=?"); } if (stat.isDefined(Stat.StatAttributes.MODE)) { sb.append(",imode=?"); } if (stat.isDefined(Stat.StatAttributes.MTIME)) { sb.append(",imtime=?"); } if (stat.isDefined(Stat.StatAttributes.ATIME)) { sb.append(",iatime=?"); } if (stat.isDefined(Stat.StatAttributes.CRTIME)) { sb.append(",icrtime=?"); } if (stat.isDefined(Stat.StatAttributes.ACCESS_LATENCY)) { sb.append(",iaccess_latency=?"); } if (stat.isDefined(Stat.StatAttributes.RETENTION_POLICY)) { sb.append(",iretention_policy=?"); } sb.append(attrUpdateSuffix); String statement = sb.toString(); PreparedStatement preparedStatement = dbConnection.prepareStatement(statement); int idx = 1; preparedStatement.setTimestamp(idx++, new Timestamp(ctime)); // NOTICE: order here MUST match the order of processing attributes above. if (stat.isDefined(Stat.StatAttributes.UID)) { preparedStatement.setInt(idx++, stat.getUid()); } if (stat.isDefined(Stat.StatAttributes.GID)) { preparedStatement.setInt(idx++, stat.getGid()); } if (stat.isDefined(Stat.StatAttributes.SIZE)) { preparedStatement.setLong(idx++, stat.getSize()); } if (stat.isDefined(Stat.StatAttributes.MODE)) { preparedStatement.setInt(idx++, stat.getMode() & UnixPermission.S_PERMS); } if (stat.isDefined(Stat.StatAttributes.MTIME)) { preparedStatement.setTimestamp(idx++, new Timestamp(stat.getMTime())); } if (stat.isDefined(Stat.StatAttributes.ATIME)) { preparedStatement.setTimestamp(idx++, new Timestamp(stat.getATime())); } if (stat.isDefined(Stat.StatAttributes.CRTIME)) { preparedStatement.setTimestamp(idx++, new Timestamp(stat.getCrTime())); } if (stat.isDefined(Stat.StatAttributes.ACCESS_LATENCY)) { preparedStatement.setInt(idx++, stat.getAccessLatency().getId()); } if (stat.isDefined(Stat.StatAttributes.RETENTION_POLICY)) { preparedStatement.setInt(idx++, stat.getRetentionPolicy().getId()); } preparedStatement.setLong(idx++, inode.ino()); return preparedStatement; }