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:com.runwaysdk.system.metadata.ontology.PostgresOntolgoyDatabase.java
@Override public void copyTerm(Map<String, Object> parameters) { Term parent = (Term) this.getParameter(parameters, DatabaseAllPathsStrategy.PARENT_PARAMETER); Term child = (Term) this.getParameter(parameters, DatabaseAllPathsStrategy.CHILD_PARAMETER); MdBusiness allPaths = (MdBusiness) this.getParameter(parameters, DatabaseAllPathsStrategy.ALL_PATHS_PARAMETER); String tableName = allPaths.getTableName(); String id = getColumn(allPaths, MetadataInfo.ID); String siteMaster = getColumn(allPaths, MetadataInfo.SITE_MASTER); String createdBy = getColumn(allPaths, MetadataInfo.CREATED_BY); String key = getColumn(allPaths, MetadataInfo.KEY); String type = getColumn(allPaths, MetadataInfo.TYPE); String domain = getColumn(allPaths, MetadataInfo.DOMAIN); String lastUpdateDate = getColumn(allPaths, MetadataInfo.LAST_UPDATE_DATE); String sequence = getColumn(allPaths, MetadataInfo.SEQUENCE); String lockedBy = getColumn(allPaths, MetadataInfo.LOCKED_BY); String createDate = getColumn(allPaths, MetadataInfo.CREATE_DATE); String owner = getColumn(allPaths, MetadataInfo.OWNER); String lastUpdatedBy = getColumn(allPaths, MetadataInfo.LAST_UPDATED_BY); String parentTerm = getColumn(allPaths, DatabaseAllPathsStrategy.PARENT_TERM_ATTR); String childTerm = getColumn(allPaths, DatabaseAllPathsStrategy.CHILD_TERM_ATTR); String allPathsRootTypeId = this.getAllPathsTypeIdRoot(allPaths); String sequenceName = this.getSequenceName(allPaths); String createdById = new String(); SessionIF sessionIF = Session.getCurrentSession(); if (sessionIF != null) { createdById = sessionIF.getUser().getId(); } else {/* www . ja v a 2 s .com*/ createdById = ServerConstants.SYSTEM_USER_ID; } // non-term values Timestamp transactionDate = new Timestamp(new Date().getTime()); String[] metadataColumns = new String[] { id, siteMaster, key, type, domain, lastUpdateDate, sequence, createdBy, lockedBy, createDate, owner, lastUpdatedBy, parentTerm, childTerm }; String insertColumns = StringUtils.join(metadataColumns, "," + NL); String childId = child.getId(); String parentId = parent.getId(); String identifierSQL = "MD5(nextval('" + sequenceName + "') || allpaths_parent." + parentTerm + " || allpaths_child." + childTerm + " ) || '" + allPathsRootTypeId + "'"; StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO " + tableName + " (" + insertColumns + ") " + NL); sql.append(" SELECT " + NL); sql.append(" " + identifierSQL + " AS newId," + NL); sql.append(" '" + CommonProperties.getDomain() + "' AS " + siteMaster + "," + NL); sql.append(" " + identifierSQL + " AS newKey," + NL); sql.append(" '" + allPaths.definesType() + "' AS \"" + type + "\"," + NL); sql.append(" '' AS " + domain + "," + NL); sql.append(" ? AS " + lastUpdateDate + "," + NL); sql.append(" NEXTVAL('" + PostgreSQL.OBJECT_UPDATE_SEQUENCE + "') AS " + sequence + "," + NL); sql.append(" '" + createdById + "' AS " + createdBy + "," + NL); sql.append(" NULL AS " + lockedBy + "," + NL); sql.append(" ? AS " + createDate + "," + NL); sql.append(" '" + createdById + "' AS \"" + owner + "\"," + NL); sql.append(" '" + createdById + "' AS " + lastUpdatedBy + "," + NL); sql.append(" allpaths_parent." + parentTerm + " AS " + parentTerm + ", " + NL); sql.append(" allpaths_child." + childTerm + " AS " + childTerm + NL); sql.append(" FROM " + NL); // Fech all of the recursive children of the given child term, including // the child term itself. sql.append(" (SELECT " + childTerm + " " + NL); sql.append(" FROM " + tableName + " " + NL); sql.append(" WHERE " + parentTerm + " = '" + childId + "' ) AS allpaths_child, " + NL); // Fech all of the recursive parents of the given new parent term, // including the new parent term itself. sql.append(" (SELECT " + parentTerm + " " + NL); sql.append(" FROM " + tableName + " " + NL); sql.append(" WHERE " + childTerm + " = '" + parentId + "' " + NL + " ) AS allpaths_parent " + NL); // Since a term can have multiple parents, a path to one of the new // parent's parents may already exist sql.append(" WHERE allpaths_parent." + parentTerm + " NOT IN " + NL); sql.append(" (SELECT " + parentTerm + " " + NL); sql.append(" FROM " + tableName + " " + NL); sql.append(" WHERE " + parentTerm + " = allpaths_parent." + parentTerm + " " + NL); sql.append(" AND " + childTerm + " = allpaths_child." + childTerm + ") " + NL); Connection conn = Database.getConnection(); PreparedStatement prepared = null; try { prepared = conn.prepareStatement(sql.toString()); prepared.setTimestamp(1, new Timestamp(transactionDate.getTime())); prepared.setTimestamp(2, new Timestamp(transactionDate.getTime())); prepared.executeUpdate(); } catch (SQLException e) { throw new ProgrammingErrorException(e); } finally { if (prepared != null) { try { prepared.close(); } catch (SQLException e) { throw new ProgrammingErrorException(e); } } } }
From source file:dk.netarkivet.common.utils.DBUtils.java
/** * Prepare a statement for iteration given a query string, fetch size * and some args.//from www. j a va2 s .co m * * NB: the provided connection is not closed. * * @param c a Database connection * @param fetchSize hint to JDBC driver on number of results to cache * @param query a query string (must not be null or empty) * @param args some args to insert into this query string (must not be null) * @return a prepared statement * @throws SQLException If unable to prepare a statement * @throws ArgumentNotValid If unable to handle type of one the args, or * the arguments are either null or an empty String. */ public static PreparedStatement prepareStatement(Connection c, int fetchSize, String query, Object... args) throws SQLException { ArgumentNotValid.checkNotNull(c, "Connection c"); ArgumentNotValid.checkPositive(fetchSize, "int fetchSize"); ArgumentNotValid.checkNotNullOrEmpty(query, "String query"); ArgumentNotValid.checkNotNull(args, "Object... args"); c.setAutoCommit(false); PreparedStatement s = c.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); s.setFetchSize(fetchSize); int i = 1; for (Object arg : args) { if (arg instanceof String) { s.setString(i, (String) arg); } else if (arg instanceof Integer) { s.setInt(i, (Integer) arg); } else if (arg instanceof Long) { s.setLong(i, (Long) arg); } else if (arg instanceof Boolean) { s.setBoolean(i, (Boolean) arg); } else if (arg instanceof Date) { s.setTimestamp(i, new Timestamp(((Date) arg).getTime())); } else { throw new ArgumentNotValid("Cannot handle type '" + arg.getClass().getName() + "'. We can only handle string, " + "int, long, date or boolean args for query: " + query); } i++; } return s; }
From source file:org.pegadi.server.score.ScoreServerImpl.java
/** * Starts score recording for a new game. The <code>Score</code> object that is * returned <i>must</i> be used when calling {@link #updateScore } and * {@link #endGame }, as each score has an unique ID. * * @param domain The domain for the game. * @return A new Score object, with the score set to 0. If the domain is not known, * this method will return <code>null</code>. *///from w w w . j a va2 s . c o m public Score startGame(final Person person, String domain) { if (domain.equals("tetris")) { final String insertSql = "insert into score_tetris (userID, score, level, linecount, starttime, active) values (?, ?, ?, ?, ?, true)"; KeyHolder keyHolder = new GeneratedKeyHolder(); // The key/id of the new score is needed template.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement statement = con.prepareStatement(insertSql, new String[] { "ID" }); statement.setString(1, person.getUsername()); statement.setLong(2, 0); // score statement.setInt(3, 1); // level statement.setInt(4, 0); // lines statement.setTimestamp(5, new Timestamp((new GregorianCalendar()).getTimeInMillis())); return statement; } }, keyHolder); int scoreId = keyHolder.getKey().intValue(); return new TetrisScore(scoreId, person.getUsername(), person.getName(), 1); } else { log.error("Domain '{}' not implemented yet!", domain); return null; } }
From source file:com.agiletec.plugins.jpcontentfeedback.aps.system.services.contentfeedback.comment.CommentDAO.java
@Override public void addComment(IComment comment) { Connection conn = null;// www . ja va2 s.c om PreparedStatement stat = null; try { conn = this.getConnection(); conn.setAutoCommit(false); stat = conn.prepareStatement(ADD_COMMENT); stat.setInt(1, comment.getId()); stat.setString(2, comment.getContentId()); stat.setTimestamp(3, new Timestamp(new Date().getTime())); stat.setString(4, comment.getComment()); stat.setInt(5, comment.getStatus()); stat.setString(6, comment.getUsername()); stat.executeUpdate(); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error adding a comment", t); throw new RuntimeException("Error adding a comment", t); } finally { closeDaoResources(null, stat, conn); } }
From source file:Model.DAO.java
public String createReservation(int idRestaurant, String name, String email, String date, String time) { String result = "No foi possivel criar a reserva"; String dateTime = date + "-" + time; SimpleDateFormat formatDateTime = new SimpleDateFormat("dd/MM/yyyy-HH:mm"); Date dateObj = null;/*from w w w .j a va 2 s . c o m*/ try { dateObj = formatDateTime.parse(dateTime); PreparedStatement stmt = this.conn.prepareStatement( "INSERT INTO Reservation(idRestaurant,Name,DateTime,Email,StatusFK)VALUES(?,?,?,?,1);"); stmt.setInt(1, idRestaurant); stmt.setString(2, name); stmt.setTimestamp(3, new Timestamp(dateObj.getTime())); stmt.setString(4, email); stmt.executeUpdate(); result = "Reserva criada com sucesso"; } catch (ParseException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:netflow.DatabaseProxy.java
public void saveNetworks(Map cache, java.util.Date dat) { if (cache.size() == 0) { log.debug("Nothing to save"); return;/*from w w w . j a v a 2 s . c om*/ } log.debug("cache size: " + cache.size() + " " + dat); String sql = getQuery("network.details.insert"); try { PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setTimestamp(2, new java.sql.Timestamp(dat.getTime())); for (Object key : cache.keySet()) { NetworkTraffic traffic = (NetworkTraffic) cache.get(key); pstmt.setInt(1, traffic.getNetworkId()); pstmt.setLong(3, traffic.getInputBytes()); pstmt.setLong(4, traffic.getOutputBytes()); pstmt.executeUpdate(); } pstmt.close(); } catch (SQLException e) { System.err.println(e.getMessage()); } }
From source file:jp.co.tis.gsp.tools.dba.dialect.SqlserverDialect.java
@Override public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType) throws SQLException { if (sqlType == UN_USABLE_TYPE) { stmt.setNull(parameterIndex, Types.NULL); } else if (StringUtil.isBlank(value) || "".equals(value)) { stmt.setNull(parameterIndex, sqlType); } else if (sqlType == Types.TIME) { stmt.setTimestamp(parameterIndex, Timestamp.valueOf("1970-01-01 " + value)); } else {/* ww w. j av a2 s . c om*/ stmt.setObject(parameterIndex, value, sqlType); } }
From source file:netflow.DatabaseProxy.java
private Timestamp getStartTimestamp(Timestamp start, Timestamp end, Integer client) { Timestamp result = null;/*from ww w .ja v a 2 s . c om*/ log.debug("Getting real start ts"); String maxDate = getQuery("start.timestamp.get"); try { PreparedStatement pst = con.prepareStatement(maxDate); pst.setTimestamp(1, start); pst.setTimestamp(2, end); pst.setInt(3, client); result = doWithStatement(pst, new ResultSetProcessor<Timestamp>() { @Override public Timestamp process(ResultSet rs) throws SQLException { if (rs.next()) return rs.getTimestamp(1); else return null; } }); } catch (SQLException e) { log.error(" Aggregation error: " + e.getMessage()); e.printStackTrace(System.err); } if (result == null) { log.debug("Impossible to find start within interval: " + start + " " + end); result = start; } log.debug("Real start is: " + result); return result; }
From source file:netflow.DatabaseProxy.java
private boolean hasRecord(Timestamp dat, String host, Integer networkId) { boolean result = false; try {//from w ww . ja v a2 s . co m PreparedStatement pstmt = con.prepareStatement(getQuery("details.exists")); pstmt.setTimestamp(1, dat); pstmt.setString(2, host); pstmt.setInt(3, networkId); return doWithStatement(pstmt, new ResultSetProcessor<Boolean>() { @Override public Boolean process(ResultSet rs) throws SQLException { return rs.next(); } }); } catch (SQLException e) { log.error("Query failed: " + e.getMessage()); } return result; }
From source file:jp.co.tis.gsp.tools.dba.dialect.MysqlDialect.java
@Override public void setObjectInStmt(PreparedStatement stmt, int parameterIndex, String value, int sqlType) throws SQLException { if (sqlType == UN_USABLE_TYPE) { stmt.setNull(parameterIndex, Types.NULL); } else if (StringUtil.isBlank(value) || "".equals(value)) { stmt.setNull(parameterIndex, sqlType); } else if (sqlType == Types.TIMESTAMP) { stmt.setTimestamp(parameterIndex, Timestamp.valueOf(value)); } else {//from w w w . j a va 2s . c o m stmt.setObject(parameterIndex, value, sqlType); } }