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:hoot.services.db.DbUtils.java
public static void batchRecordsDirectNodes(final long mapId, final List<?> records, final RecordBatchType recordBatchType, Connection conn, int maxRecordBatchSize) throws Exception { PreparedStatement ps = null; try {/* w ww. ja va 2s. c o m*/ String sql = null; long execResult = -1; //conn.setAutoCommit(false); int count = 0; switch (recordBatchType) { case INSERT: sql = "insert into current_nodes_" + mapId + " (id, latitude, " + "longitude, changeset_id, visible, \"timestamp\", tile, version, tags) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?)"; ps = conn.prepareStatement(sql); for (Object o : records) { CurrentNodes node = (CurrentNodes) o; ps.setLong(1, node.getId()); ps.setInt(2, node.getLatitude()); ps.setInt(3, node.getLongitude()); ps.setLong(4, node.getChangesetId()); ps.setBoolean(5, node.getVisible()); ps.setTimestamp(6, node.getTimestamp()); ps.setLong(7, node.getTile()); ps.setLong(8, node.getVersion()); Map<String, String> tags = (Map<String, String>) node.getTags(); String hstoreStr = ""; Iterator it = tags.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if (hstoreStr.length() > 0) { hstoreStr += ","; } hstoreStr += "\"" + pairs.getKey() + "\"=>\"" + pairs.getValue() + "\""; } ps.setObject(9, hstoreStr, Types.OTHER); ps.addBatch(); if (maxRecordBatchSize > -1) { if (++count % maxRecordBatchSize == 0) { ps.executeBatch(); //conn.commit(); } } } break; case UPDATE: sql = "update current_nodes_" + mapId + " set latitude=?, " + "longitude=?, changeset_id=?, visible=?, \"timestamp\"=?, tile=?, version=?, tags=? " + "where id=?"; ps = conn.prepareStatement(sql); for (Object o : records) { CurrentNodes node = (CurrentNodes) o; ps.setInt(1, node.getLatitude()); ps.setInt(2, node.getLongitude()); ps.setLong(3, node.getChangesetId()); ps.setBoolean(4, node.getVisible()); ps.setTimestamp(5, node.getTimestamp()); ps.setLong(6, node.getTile()); ps.setLong(7, node.getVersion()); Map<String, String> tags = (Map<String, String>) node.getTags(); String hstoreStr = ""; Iterator it = tags.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if (hstoreStr.length() > 0) { hstoreStr += ","; } hstoreStr += "\"" + pairs.getKey() + "\"=>\"" + pairs.getValue() + "\""; } ps.setObject(8, hstoreStr, Types.OTHER); ps.setLong(9, node.getId()); ps.addBatch(); if (maxRecordBatchSize > -1) { if (++count % maxRecordBatchSize == 0) { ps.executeBatch(); //conn.commit(); ps.clearBatch(); } } } break; case DELETE: sql = "delete from current_nodes_" + mapId + " where id=?"; ps = conn.prepareStatement(sql); for (Object o : records) { CurrentNodes node = (CurrentNodes) o; ps.setLong(1, node.getId()); ps.addBatch(); if (maxRecordBatchSize > -1) { if (++count % maxRecordBatchSize == 0) { ps.executeBatch(); //conn.commit(); ps.clearBatch(); } } } break; default: throw new Exception(""); } ps.executeBatch(); //conn.commit(); } catch (Exception e) { //conn.rollback(); String msg = "Error executing batch query."; msg += " " + e.getMessage(); msg += " Cause:" + e.getCause().toString(); throw new Exception(msg); } finally { if (ps != null) { ps.close(); } //conn.setAutoCommit(true); } }
From source file:no.polaric.aprsdb.MyDBSession.java
/** * Get points that were transmitted via a certain digipeater during a certain time span. *//* w w w . j a v a 2s .c om*/ public DbList<TPoint> getPointsVia(String digi, Reference uleft, Reference lright, java.util.Date from, java.util.Date to) throws java.sql.SQLException { _log.debug("MyDbSession", "getPointsVia: " + digi + ", " + df.format(from) + " - " + df.format(to)); PreparedStatement stmt = getCon().prepareStatement( " SELECT DISTINCT position " + " FROM \"AprsPacket\" p, \"PosReport\" r " + " WHERE p.src=r.src " + " AND p.time=r.rtime " + " AND (substring(p.path, '([^,\\*]+).*\\*.*')=? OR " + " (substring(p.ipath, 'qAR,([^,\\*]+).*')=? AND p.path !~ '.*\\*.*')) " + " AND position && ST_MakeEnvelope(?, ?, ?, ?, 4326) " + " AND p.time > ? AND p.time < ? LIMIT 10000", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); stmt.setString(1, digi); stmt.setString(2, digi); LatLng ul = uleft.toLatLng(); LatLng lr = lright.toLatLng(); stmt.setDouble(3, ul.getLng()); stmt.setDouble(4, ul.getLat()); stmt.setDouble(5, lr.getLng()); stmt.setDouble(6, lr.getLat()); stmt.setTimestamp(7, date2ts(from)); stmt.setTimestamp(8, date2ts(to)); stmt.setMaxRows(10000); return new DbList(stmt.executeQuery(), rs -> { return new TPoint(null, getRef(rs, "position")); }); }
From source file:com.novartis.opensource.yada.adaptor.JDBCAdaptor.java
/** * Sets a {@code ?t} parameter value mapped to the correct {@link java.sql.Types#TIMESTAMP} JDBC setter. * @param pstmt the statement in which to set the parameter values * @param index the current parameter//from w w w . ja v a2s . com * @param type the data type of the parameter (retained here for logging) * @param val the value to set * @throws SQLException when a parameter cannot be set, for instance if the data type is wrong or unsupported * @since 5.1.0 */ protected void setTimestampParameter(PreparedStatement pstmt, int index, char type, String val) throws SQLException { if (EMPTY.equals(val) || val == null) { pstmt.setNull(index, java.sql.Types.TIMESTAMP); } else { SimpleDateFormat sdf = new SimpleDateFormat(STANDARD_TIMESTAMP_FMT); ParsePosition pp = new ParsePosition(0); Date dateVal = sdf.parse(val, pp); if (dateVal != null) { long t = dateVal.getTime(); java.sql.Timestamp sqlDateVal = new java.sql.Timestamp(t); pstmt.setTimestamp(index, sqlDateVal); } } }
From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaDropDao.java
/** * Insert new drops in a single batch statement * /*from w ww. ja v a 2 s . c om*/ * @param newDropIndex * @param drops */ private void batchInsert(final Map<String, List<Integer>> newDropIndex, final List<Drop> drops, Sequence seq) { final List<String> hashes = new ArrayList<String>(); hashes.addAll(newDropIndex.keySet()); final long startKey = sequenceDao.getIds(seq, hashes.size()); String sql = "INSERT INTO droplets (id, channel, droplet_hash, " + "droplet_orig_id, droplet_title, " + "droplet_content, droplet_date_pub, droplet_date_add, " + "identity_id) VALUES (?,?,?,?,?,?,?,?,?)"; jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { String hash = hashes.get(i); // Update drops with the newly generated id for (int index : newDropIndex.get(hash)) { drops.get(index).setId(startKey + i); } Drop drop = drops.get(newDropIndex.get(hash).get(0)); ps.setLong(1, drop.getId()); ps.setString(2, drop.getChannel()); ps.setString(3, drop.getHash()); ps.setString(4, drop.getOriginalId()); ps.setString(5, drop.getTitle()); ps.setString(6, drop.getContent()); ps.setTimestamp(7, new java.sql.Timestamp(drop.getDatePublished().getTime())); ps.setTimestamp(8, new java.sql.Timestamp((new Date()).getTime())); ps.setLong(9, drop.getIdentity().getId()); } public int getBatchSize() { return hashes.size(); } }); logger.debug("Successfully saved {} drops in the database", hashes.size()); }
From source file:com.alfaariss.oa.util.saml2.storage.artifact.jdbc.JDBCArtifactMapFactory.java
/** * Store the given artifact in the JDBC resource. * @see org.opensaml.common.binding.artifact.SAMLArtifactMap#put( * java.lang.String, java.lang.String, java.lang.String, * org.opensaml.common.SAMLObject)/*from ww w . ja va2 s. co m*/ */ public void put(String artifact, String relyingPartyId, String issuerId, SAMLObject samlMessage) throws MarshallingException { if (artifact == null) throw new IllegalArgumentException("Suplied artifact is empty"); if (samlMessage == null) throw new IllegalArgumentException("Suplied samlMessage is empty"); if (relyingPartyId == null) _logger.debug("Suplied relyingPartyId is empty"); if (issuerId == null) _logger.debug("Suplied issuerId is empty"); Connection oConnection = null; PreparedStatement psInsert = null; try { oConnection = _oDataSource.getConnection(); //Serialize message //TODO EVB: store object bytes instead of serialization StringWriter writer = new StringWriter(); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(samlMessage); XMLHelper.writeNode(marshaller.marshall(samlMessage), writer); String serializedMessage = writer.toString(); // Update expiration time and id long expiration = System.currentTimeMillis() + _lExpiration; //Create statement psInsert = oConnection.prepareStatement(_sInsertQuery); psInsert.setString(1, artifact); psInsert.setString(2, issuerId); psInsert.setString(3, relyingPartyId); psInsert.setString(4, serializedMessage); psInsert.setTimestamp(5, new Timestamp(expiration)); int i = psInsert.executeUpdate(); _logger.debug(i + " new artifact stored: " + artifact); } catch (SQLException e) { _logger.error("Could not execute insert query: " + _sInsertQuery, e); } finally { try { if (psInsert != null) psInsert.close(); } catch (SQLException e) { _logger.debug("Could not close insert statement", e); } try { if (oConnection != null) oConnection.close(); } catch (SQLException e) { _logger.debug("Could not close connection", e); } } }
From source file:com.sinet.gage.dao.DomainsRepository.java
/** * //from ww w . j a va 2 s . co m * @param domains */ public void updateDomains(List<Domain> domains) { try { jdbcTemplate.batchUpdate(DOMAINS_FULL_UPDATE_SQL, new BatchPreparedStatementSetter() { public int getBatchSize() { if (domains == null) return 0; return domains.size(); } @Override public void setValues(PreparedStatement ps, int i) throws SQLException { Domain domain = domains.get(i); ps.setObject(1, domain.getGuid()); ps.setString(2, domain.getDomainName()); ps.setString(3, domain.getLoginPrefix()); ps.setLong(4, domain.getFlag()); ps.setString(5, domain.getDomainType()); ps.setLong(6, domain.getParentDomainId()); ps.setString(7, domain.getParentDomainName()); ps.setLong(8, domain.getStateDomainId()); ps.setString(9, domain.getStateDomainName()); ps.setString(10, domain.getLicenseType()); ps.setString(11, domain.getLicensePoolType()); ps.setInt(12, domain.getNoOfLicense()); ps.setBoolean(13, domain.isPilot()); ps.setDate(14, domain.getPilotStartDate()); ps.setDate(15, domain.getPilotEndDate()); ps.setBoolean(16, domain.isFullSubscription()); ps.setObject(17, domain.getSubscriptionStartDate()); ps.setObject(18, domain.getSubscriptionEndDate()); ps.setLong(19, domain.getModifierUserId()); ps.setTimestamp(20, domain.getModifiedDate()); ps.setLong(21, domain.getDomainId()); } }); } catch (Exception e) { log.error("Error in updating Domains", e); } }
From source file:com.buckwa.dao.impl.excise4.Form23DaoImpl.java
@Override public void update(final Form23 form23) { logger.info("update"); String user = ""; try {// w w w. j av a 2s . c o m user = BuckWaUtils.getUserNameFromContext(); } catch (BuckWaException e) { e.printStackTrace(); } final String userName = user; final Timestamp currentDate = new Timestamp(System.currentTimeMillis()); if (BeanUtils.isEmpty(form23.getCodeNo())) { form23.setCodeNo("" + System.currentTimeMillis()); } String sqlform23 = "UPDATE `form23` SET `factory_id`=?,`update_date`=?,`update_by`=? " + " ,`totalScrap`=?,`part4flag`=?,`part4fullName`=?,`part4Date`=? ," + " `part5flag`=?,`part5licenseNo`=?,`part5licenseDate`=?,`part5billingNo`=?,`part5billingDate`=?,`part5amount`=?,`part5Date`=?," + " `part6flag`=?,`part6Date`=?,`step`=?,`codeNo`=? " + " WHERE `form23_id`=?"; logger.info("update: " + sqlform23); this.jdbcTemplate.update(sqlform23, new Object[] { form23.getFactory().getFactoryId(), currentDate, userName, form23.getTotalScrap(), form23.getPart4flag(), form23.getPart4fullName(), currentDate, form23.getPart5flag(), form23.getPart5licenseNo(), getDateFormString(form23.getPart5licenseDate()), form23.getPart5billingNo(), getDateFormString(form23.getPart5billingDate()), form23.getPart5amount(), currentDate, form23.getPart6flag(), currentDate, form23.getStep(), form23.getCodeNo(), form23.getForm23Id() }); //ID PRODUCT String productSql = "UPDATE `form23_product` SET `seq`=?,`productName`=?,`size`=?,`bandColor`=?,`backgroudColor`=?,`licenseNo`=?" + ",`grossnumber200`=?,`grossnumber400`=?,`corkScrap`=?,`totalScrap`=?,`update_date`=?,`update_by`=? " + "WHERE `product_id`=?"; final StringBuilder psql = new StringBuilder(); psql.append( "INSERT INTO `form23_product`(`form23_id`,`seq`,`productName`,`size`,`bandColor`,`backgroudColor`,`licenseNo`,`grossnumber200`,`grossnumber400`,`corkScrap`,`totalScrap`,`create_date`,`create_by`, `update_date`,`update_by`,`product_id`) ") .append("VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)"); List<Product> products = form23.getProductList(); if (products != null) { for (final Product p : products) { if (BeanUtils.isEmpty(p.getProcuctId())) { logger.info("create"); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(psql.toString(), Statement.RETURN_GENERATED_KEYS); long returnidform23 = form23.getForm23Id(); ps.setLong(1, returnidform23); ps.setString(2, p.getSeq()); ps.setString(3, p.getProductName()); ps.setString(4, p.getSize()); ps.setString(5, p.getBandColor()); ps.setString(6, p.getBackgroudColor()); ps.setString(7, p.getLicenseNo()); ps.setBigDecimal(8, p.getGrossnumber200()); ps.setBigDecimal(9, p.getGrossnumber400()); ps.setBigDecimal(10, p.getCorkScrap()); ps.setBigDecimal(11, p.getTotalScrap()); ps.setTimestamp(12, currentDate); ps.setString(13, userName); ps.setTimestamp(14, currentDate); ps.setString(15, userName); return ps; } }, keyHolder); long returnidproduct = keyHolder.getKey().longValue(); p.setProcuctId(returnidproduct); logger.info("returnidproduct : " + returnidproduct); } else { logger.info("update"); this.jdbcTemplate.update(productSql, new Object[] { p.getSeq(), p.getProductName(), p.getSize(), p.getBandColor(), p.getBackgroudColor(), p.getLicenseNo(), p.getGrossnumber200(), p.getGrossnumber400(), p.getCorkScrap(), p.getTotalScrap(), currentDate, userName, p.getProcuctId() }); } } } }
From source file:com.buckwa.dao.impl.excise4.Form24DaoImpl.java
@Override public void update(final Form24 form24) { logger.info("update"); String user = ""; try {/*w w w. j a v a 2s . c o m*/ user = BuckWaUtils.getUserNameFromContext(); } catch (BuckWaException e) { e.printStackTrace(); } final String userName = user; final Timestamp currentDate = new Timestamp(System.currentTimeMillis()); String sqlform24 = "UPDATE `form24` SET `factory_id`=?,`update_date`=?,`update_by`=? WHERE `form24_id`=?"; logger.info("update: " + sqlform24); this.jdbcTemplate.update(sqlform24, new Object[] { form24.getFactory().getFactoryId(), currentDate, userName, form24.getForm24Id() }); //ID PRODUCT String productSql = "UPDATE `form24_product` SET `seq`=?,`productName`=?,`size`=?,`bandColor`=?,`backgroudColor`=?,`licenseNo`=?" + ",`grossnumber200`=?,`grossnumber400`=?,`corkScrap`=?,`totalScrap`=?,`update_date`=?,`update_by`=? " + "WHERE `product_id`=?"; final StringBuilder psql = new StringBuilder(); psql.append( "INSERT INTO `form24_product`(`form24_id`,`seq`,`productName`,`size`,`bandColor`,`backgroudColor`,`licenseNo`,`grossnumber200`,`grossnumber400`,`corkScrap`,`totalScrap`,`create_date`,`create_by`, `update_date`,`update_by`,`product_id`) ") .append("VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)"); List<Product> products = form24.getProductList(); if (products != null) { for (final Product p : products) { if (BeanUtils.isEmpty(p.getProcuctId())) { logger.info("create"); KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(psql.toString(), Statement.RETURN_GENERATED_KEYS); long returnidform24 = form24.getForm24Id(); ps.setLong(1, returnidform24); ps.setString(2, p.getSeq()); ps.setString(3, p.getProductName()); ps.setString(4, p.getSize()); ps.setString(5, p.getBandColor()); ps.setString(6, p.getBackgroudColor()); ps.setString(7, p.getLicenseNo()); ps.setBigDecimal(8, p.getGrossnumber200()); ps.setBigDecimal(9, p.getGrossnumber400()); ps.setBigDecimal(10, p.getCorkScrap()); ps.setBigDecimal(11, p.getTotalScrap()); ps.setTimestamp(12, currentDate); ps.setString(13, userName); ps.setTimestamp(14, currentDate); ps.setString(15, userName); return ps; } }, keyHolder); long returnidproduct = keyHolder.getKey().longValue(); p.setProcuctId(returnidproduct); logger.info("returnidproduct : " + returnidproduct); } else { logger.info("update"); this.jdbcTemplate.update(productSql, new Object[] { p.getSeq(), p.getProductName(), p.getSize(), p.getBandColor(), p.getBackgroudColor(), p.getLicenseNo(), p.getGrossnumber200(), p.getGrossnumber400(), p.getCorkScrap(), p.getTotalScrap(), currentDate, userName, p.getProcuctId() }); } } } }
From source file:org.pegadi.server.article.ArticleServerImpl.java
/** * Saves a new or updates an existing article. If the articleID is 0, a new article is inserted into the database * and the new ID is returned. Else the article will be updated. This method will not save or modyify * the article text. The exception is when the article type changes. * * @param article The article to save./* w w w.j av a 2 s. co m*/ * @return New articleID if new article is created or 0 for successful save of existing article. Returnvalue less than 0 * means that something was wrong, and the article was not successfully saved. */ public int saveArticle(final Article article) { if (article == null) { // huh - no article? log.error("error - can't save a non-exixting article..."); return -1; } else { log.info("Saving article with ID=" + article.getId()); final String journalist = article.getJournalist() != null ? article.getJournalist().getUsername() : null; final String photographer = article.getPhotographer() != null ? article.getPhotographer().getUsername() : null; final int publication = article.getPublication() != null ? article.getPublication().getId() : 0; final int articleType = article.getArticleType() != null ? article.getArticleType().getId() : 0; final String text = article.getText() != null ? article.getText() : ""; final int department = article.getSection() != null ? article.getSection().getId() : 0; final int articlestatus = article.getArticleStatus() != null ? article.getArticleStatus().getId() : 1; if (article.getId() == 0) { // no ID means insert a new article KeyHolder keyHolder = new GeneratedKeyHolder(); final String insert = "INSERT INTO Article (name, refJournalist, refPhotographer, refPublication, description, refArticleType, wantedCharacters, wantedPages,articlexml, refSection, refStatus, lastSaved) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"; template.getJdbcOperations().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(insert, new String[] { "ID" }); ps.setString(1, article.getName()); ps.setString(2, journalist); ps.setString(3, photographer); ps.setInt(4, publication); ps.setString(5, article.getDescription()); ps.setInt(6, articleType); ps.setInt(7, article.getWantedNumberOfCharacters()); ps.setFloat(8, article.getWantedNumberOfPages()); ps.setString(9, text); ps.setInt(10, department); ps.setInt(11, articlestatus); ps.setTimestamp(12, new Timestamp((new Date()).getTime())); return ps; } }, keyHolder); int articleId = keyHolder.getKey().intValue(); log.info("Saved a new article, and gave it ID={}", articleId); return articleId; } else { // Save existing article int articletypeOld = template.queryForInt("SELECT refArticleType FROM Article WHERE ID=:id", Collections.singletonMap("id", article.getId())); if (article.getArticleType() != null) { int AT = article.getArticleType().getId(); // Important to do this before the article text is set if (AT != articletypeOld && article.hasText()) { changeArticleType(article, AT); } } doBackup(article.getId(), article.getText()); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", article.getName()); parameters.put("text", article.getText()); parameters.put("department", department); parameters.put("journalist", journalist); parameters.put("photographer", photographer); parameters.put("publication", publication); parameters.put("description", article.getDescription()); parameters.put("wantedNumbeOfCharacters", article.getWantedNumberOfCharacters()); parameters.put("wantedNumberOfPages", article.getWantedNumberOfPages()); parameters.put("articleType", articleType); parameters.put("articleStatus", articlestatus); parameters.put("lastSaved", new Timestamp((new Date()).getTime())); parameters.put("id", article.getId()); template.update("UPDATE Article " + "SET name=:name, articlexml=:text, refSection=:department, " + "refJournalist=:journalist, refPhotographer=:photographer, " + "refPublication=:publication, description=:description, " + "wantedCharacters=:wantedNumbeOfCharacters, wantedPages=:wantedNumberOfPages, " + "refArticleType=:articleType, refStatus=:articleStatus, " + "lastSaved=:lastSaved " + "WHERE ID=:id", parameters); } } return 0; }
From source file:se.technipelago.weather.chart.Generator.java
private HiLow getHighLow(Date from, Date to, String column, boolean max) { PreparedStatement stmt = null; ResultSet result = null;//from w w w.ja v a2s. c o m HiLow hilo = null; String func = max ? "DESC" : "ASC"; init(); try { stmt = conn.prepareStatement("SELECT ts, " + column + " FROM archive WHERE ts BETWEEN ? AND ? ORDER BY " + column + " " + func + ", ts ASC"); stmt.setTimestamp(1, new java.sql.Timestamp(from.getTime())); stmt.setTimestamp(2, new java.sql.Timestamp(to.getTime())); result = stmt.executeQuery(); if (result.next()) { hilo = new HiLow(result.getTimestamp(1), result.getFloat(2)); } } 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 hilo; }