List of usage examples for java.sql PreparedStatement setLong
void setLong(int parameterIndex, long x) throws SQLException;
long
value. From source file:com.flexive.core.storage.genericSQL.GenericLockStorage.java
/** * {@inheritDoc}/*from www . java2s .co m*/ */ @Override @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public List<FxLock> getUserLocks(Connection con, long userId) { List<FxLock> result = new ArrayList<FxLock>(10); PreparedStatement ps = null; try { // 1 2 3 4 5 6 ps = con.prepareStatement("SELECT LOCKTYPE,CREATED_AT,EXPIRES_AT,LOCK_ID,LOCK_VER,LOCK_RESOURCE FROM " + TBL_LOCKS + " WHERE USER_ID=?"); ps.setLong(1, userId); ResultSet rs = ps.executeQuery(); while (rs != null && rs.next()) { Object res = rs.getString(6); if (rs.wasNull()) res = new FxPK(rs.getLong(4), rs.getInt(5)); try { result.add(new FxLock(FxLockType.getById(rs.getInt(1)), rs.getLong(2), rs.getLong(3), userId, res)); } catch (FxLockException e) { LOG.warn(e); } } } catch (SQLException e) { throw new FxDbException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException(); } finally { Database.closeObjects(GenericLockStorage.class, null, ps); } return result; }
From source file:de.ingrid.importer.udk.strategy.v30.IDCStrategy3_0_1.java
protected void migrateSpatialSystem() throws Exception { if (log.isInfoEnabled()) { log.info("Migrate Spatial System to new table (now n:1)..."); }//from w w w . java 2 s . c o m // use PreparedStatement to avoid problems when value String contains "'" !!! String psSql = "INSERT INTO spatial_system (id, obj_id, line, referencesystem_key, referencesystem_value) " + "VALUES (?, ?, 1, ?, ?)"; PreparedStatement ps = jdbc.prepareStatement(psSql); String sql = "select distinct id, obj_id, referencesystem_key, referencesystem_value " + "from t011_obj_geo"; Statement st = jdbc.createStatement(); ResultSet rs = jdbc.executeQuery(sql, st); int numMigrated = 0; while (rs.next()) { long objId = rs.getLong("obj_id"); int referencesystemKey = rs.getInt("referencesystem_key"); String referencesystemValue = rs.getString("referencesystem_value"); if (referencesystemKey == 0) { referencesystemKey = -1; } if (referencesystemKey > 0 || referencesystemValue != null) { ps.setLong(1, getNextId()); ps.setLong(2, objId); ps.setInt(3, referencesystemKey); ps.setString(4, referencesystemValue); ps.executeUpdate(); numMigrated++; if (log.isDebugEnabled()) { log.debug("Migrated spatial system (key:" + referencesystemKey + ", value:'" + referencesystemValue + "') of object with id:" + objId + ")."); } } } rs.close(); st.close(); ps.close(); if (log.isDebugEnabled()) { log.debug("Migrated " + numMigrated + " spatial systems."); } if (log.isInfoEnabled()) { log.info("Migrate Spatial System to new table (now n:1)... done"); } }
From source file:com.flexive.core.storage.genericSQL.GenericLockStorage.java
/** * {@inheritDoc}// w ww . ja va2 s .com */ @Override @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public FxLock takeOver(Connection con, FxLock lock, long duration) throws FxLockException { final UserTicket ticket = FxContext.getUserTicket(); final boolean allowTakeOver = lock.getLockType() == FxLockType.Loose || lock.isExpired() || (lock.getLockType() == FxLockType.Permanent && (ticket.isGlobalSupervisor() || ticket.isMandatorSupervisor())); if (!allowTakeOver) { if (lock.isContentLock()) throw new FxLockException("ex.lock.takeOver.denied.pk", lock.getLockedPK()); else throw new FxLockException("ex.lock.takeOver.denied.resource", lock.getLockedResource()); } //permission checks if content lock if (!(ticket.isGlobalSupervisor() || ticket.isMandatorSupervisor()) && lock.isContentLock()) checkEditPermission(con, lock.getLockedPK(), ticket); PreparedStatement ps = null; try { ps = con.prepareStatement( "UPDATE " + TBL_LOCKS + " SET USER_ID=?" + (duration > 0 ? ",EXPIRES_AT=?" : "") + " WHERE " + (lock.isContentLock() ? "LOCK_ID=? AND LOCK_VER=?" : "LOCK_RESOURCE=?")); ps.setLong(1, ticket.getUserId()); int startIdx = 2; if (duration > 0) { ps.setLong(2, lock.getExpiresTimestamp() + duration); startIdx++; } if (lock.isContentLock()) { ps.setLong(startIdx, lock.getLockedPK().getId()); ps.setInt(startIdx + 1, lock.getLockedPK().getVersion()); } else ps.setString(startIdx, lock.getLockedResource()); if (ps.executeUpdate() != 1) throw new FxLockException("ex.lock.takeOverFailed.noRows", lock.isContentLock() ? lock.getLockedPK() : lock.getLockedResource()); } catch (SQLException e) { throw new FxDbException(e, "ex.db.sqlError", e.getMessage()).asRuntimeException(); } finally { Database.closeObjects(GenericLockStorage.class, null, ps); } Object obj = lock.isContentLock() ? lock.getLockedPK() : lock.getLockedResource(); return new FxLock(lock.getLockType(), lock.getCreatedTimestamp(), duration > 0 ? lock.getExpiresTimestamp() + duration : lock.getExpiresTimestamp(), ticket.getUserId(), obj); }
From source file:com.l2jfree.gameserver.model.entity.CCHSiege.java
public void saveSiegeDate() { if (_startSiegeTask.isScheduled()) _startSiegeTask.schedule(1000);// w w w . j a va 2s . c o m Connection con = null; try { con = L2DatabaseFactory.getInstance().getConnection(con); PreparedStatement statement = con.prepareStatement( "UPDATE clanhall_sieges SET siegeDate=?,regTimeEnd=?,regTimeOver=? WHERE hallId=?"); statement.setLong(1, getSiegeDate().getTimeInMillis()); statement.setLong(2, getTimeRegistrationOverDate().getTimeInMillis()); statement.setString(3, String.valueOf(getIsTimeRegistrationOver())); statement.setInt(4, _hideout.getId()); statement.execute(); statement.close(); } catch (Exception e) { _log.error("Exception: saveSiegeDate(): " + e.getMessage(), e); } finally { L2DatabaseFactory.close(con); } }
From source file:dk.netarkivet.harvester.datamodel.extendedfield.ExtendedFieldValueDBDAO.java
/** * Read a ExtendedFieldValue in persistent storage. * @param aConnection an open connection to the HarvestDatabase * @param aExtendedFieldValue The ExtendedFieldValue to update * @param aCommit Should we commit this or not * @throws SQLException In case of database problems. *//* www . j av a2s .com*/ public void update(Connection aConnection, ExtendedFieldValue aExtendedFieldValue, boolean aCommit) throws SQLException { PreparedStatement statement = null; final Long extendedfieldvalueId = aExtendedFieldValue.getExtendedFieldID(); if (!exists(aConnection, extendedfieldvalueId)) { throw new UnknownID( "Extended Field Value id " + extendedfieldvalueId + " is not known in persistent storage"); } aConnection.setAutoCommit(false); statement = aConnection.prepareStatement( "" + "UPDATE extendedfieldvalue " + "SET extendedfield_id = ?, " + " instance_id = ?, " + " content = ? " + "WHERE extendedfieldvalue_id = ? and instance_id = ?"); statement.setLong(1, aExtendedFieldValue.getExtendedFieldID()); statement.setLong(2, aExtendedFieldValue.getInstanceID()); statement.setString(3, aExtendedFieldValue.getContent()); statement.setLong(4, aExtendedFieldValue.getExtendedFieldValueID()); statement.setLong(5, aExtendedFieldValue.getInstanceID()); statement.executeUpdate(); if (aCommit) { aConnection.commit(); } }
From source file:com.pactera.edg.am.metamanager.extractor.dao.helper.CreateMetadataAlterHelper.java
protected void doInPreparedStatement(PreparedStatement ps, String metaModelCode, boolean hasChildMetaModel, List<AbstractMetadata> metadatas) throws SQLException { try {//from w w w .j a v a 2 s . c o m for (AbstractMetadata metadata : metadatas) { // ?ID String sequenceId = sequenceDao.getUuid(); ps.setString(1, sequenceId); // ID ps.setString(3, taskInstanceId); // ?ID ps.setString(4, metadata.getId()); // ps.setString(5, metaModelCode); // ID ps.setString(7, userId); // : ALTERATION_TIME ps.setLong(9, startTime); // ? ? 2010-05-18 fbchen //ps.setString(3, genAttrs(metadata)); setPs(ps, metadata, metaModelCode, hasChildMetaModel); String parentId = metadata.getParentMetadata().getId(); if (parentId == null || parentId.equals("")) { parentId = "0"; } ps.setString(11, parentId); ps.addBatch(); ps.clearParameters(); if (++super.count % super.batchSize == 0) { ps.executeBatch(); ps.clearBatch(); } } } catch (SQLException e) { // ??,????,,?? log.warn("??!", e); } }
From source file:com.softberries.klerk.dao.DocumentItemDao.java
public void create(DocumentItem c, QueryRunner run, Connection conn, ResultSet generatedKeys) throws SQLException { PreparedStatement st = conn.prepareStatement(SQL_INSERT_DOCUMENTITEM, Statement.RETURN_GENERATED_KEYS); st.setString(1, c.getPriceNetSingle()); st.setString(2, c.getPriceGrossSingle()); st.setString(3, c.getPriceTaxSingle()); st.setString(4, c.getPriceNetAll()); st.setString(5, c.getPriceGrossAll()); st.setString(6, c.getPriceTaxAll()); st.setString(7, c.getTaxValue());// w w w. j a va2s . c o m st.setString(8, c.getQuantity()); if (c.getProduct().getId().longValue() == 0 && c.getDocument_id().longValue() == 0) { throw new SQLException( "For DocumentItem corresponding product and document it belongs to need to be specified"); } if (c.getProduct().getId() != 0) { st.setLong(9, c.getProduct().getId()); } else { st.setNull(9, java.sql.Types.NUMERIC); } if (c.getDocument_id().longValue() != 0) { st.setLong(10, c.getDocument_id()); } else { st.setNull(10, java.sql.Types.NUMERIC); } st.setString(11, c.getProduct().getName()); // run the query int i = st.executeUpdate(); System.out.println("i: " + i); if (i == -1) { System.out.println("db error : " + SQL_INSERT_DOCUMENTITEM); } generatedKeys = st.getGeneratedKeys(); if (generatedKeys.next()) { c.setId(generatedKeys.getLong(1)); } else { throw new SQLException("Creating user failed, no generated key obtained."); } }
From source file:com.flexive.core.conversion.FxTypeConverter.java
/** * {@inheritDoc}/*from w ww . ja va 2s. c o m*/ */ @Override @SuppressWarnings({ "ThrowableInstanceNeverThrown" }) public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext ctx) { final FxEnvironment env = CacheAdmin.getEnvironment(); String name = reader.getAttribute("name"); boolean existing = env.typeExists(name); FxTypeEdit typeEdit = existing ? env.getType(name).asEditable() : null; final TypeEngine typeEngine = EJBLookup.getTypeEngine(); FxType parent = null; if (Boolean.valueOf(reader.getAttribute("derived"))) { //this value can not be changed for existing types final String parentType = reader.getAttribute("parent"); if (!FxType.ROOT.equals(parentType)) parent = env.getType(parentType); } ACL acl = env.getACL(reader.getAttribute("acl")); boolean hasDefaultACL = Boolean.valueOf(reader.getAttribute("hasdefacl")); ACL defACL = null; if (hasDefaultACL) defACL = env.getACL(reader.getAttribute("defacl")); TypeCategory cat = TypeCategory.valueOf(reader.getAttribute("category")); LanguageMode langMode = LanguageMode.valueOf(reader.getAttribute("languageMode")); long maxVersions = Long.valueOf(reader.getAttribute("maxVersions")); TypeMode mode = TypeMode.valueOf(reader.getAttribute("mode")); TypeState state = TypeState.valueOf(reader.getAttribute("state")); TypeStorageMode storageMode = TypeStorageMode.valueOf(reader.getAttribute("storageMode")); Workflow workflow = env.getWorkflow(reader.getAttribute("workflow")); byte permissions = FxPermissionUtils.encodeTypePermissions(Boolean.valueOf(reader.getAttribute("permInst")), Boolean.valueOf(reader.getAttribute("permProp")), Boolean.valueOf(reader.getAttribute("permStep")), Boolean.valueOf(reader.getAttribute("permType"))); boolean trackHistory = Boolean.valueOf(reader.getAttribute("trackHistory")); long historyAge = 0; if (trackHistory) historyAge = Long.valueOf(reader.getAttribute("historyAge")); boolean autoVersion = containsAttribute(reader, "autoVersion") ? Boolean.valueOf(reader.getAttribute("autoVersion")) : false; boolean includedInSuperTypeQueries = containsAttribute(reader, "autoVersion") ? Boolean.valueOf(reader.getAttribute("includedInSuperTypeQueries")) : true; int maxRelSource = -1; int maxRelDest = -1; FxString label = null; List<FxTypeScriptImportMapping> scriptMapping = null; if (!existing) { typeEdit = FxTypeEdit.createNew(name, label, acl, defACL, workflow, parent, false, storageMode, cat, mode, langMode, state, permissions, trackHistory, historyAge, maxVersions, autoVersion, maxRelSource, maxRelDest); typeEdit.setIncludedInSupertypeQueries(includedInSuperTypeQueries); typeEdit.setLifeCycleInfo(LifeCycleInfoImpl.createNew(FxContext.getUserTicket())); } if (existing) { typeEdit.setACL(acl); typeEdit.setDefaultInstanceACL(defACL); typeEdit.setCategory(cat); typeEdit.setLanguage(langMode); typeEdit.setMaxVersions(maxVersions); typeEdit.setMode(mode); typeEdit.setState(state); //storage mode can not be changed for existing types (yet) typeEdit.setWorkflow(workflow); typeEdit.setPermissions(permissions); typeEdit.setTrackHistory(trackHistory); typeEdit.setHistoryAge(historyAge); } ctx.put(ConversionEngine.KEY_TYPE, typeEdit); boolean processAssignments = false; while (reader.hasMoreChildren()) { reader.moveDown(); String node = reader.getNodeName(); if ("relations".equals(node)) { maxRelSource = Integer.valueOf(reader.getAttribute("maxSrc")); maxRelDest = Integer.valueOf(reader.getAttribute("maxDst")); typeEdit.setMaxRelSource(maxRelSource); typeEdit.setMaxRelDestination(maxRelDest); } else if ("relation".equals(node)) { try { typeEdit.addRelation(new FxTypeRelation(new FxPreloadType(reader.getAttribute("src")), new FxPreloadType(reader.getAttribute("dst")), Long.valueOf(reader.getAttribute("maxSrc")), Long.valueOf(reader.getAttribute("maxDst")))); } catch (FxInvalidParameterException e) { throw e.asRuntimeException(); } } else if ("label".equals(node)) { typeEdit.setLabel((FxString) ctx.convertAnother(this, FxValue.class)); } else if (ConversionEngine.KEY_LCI.equals(node)) { ctx.convertAnother(this, LifeCycleInfo.class); } else if ("scriptEvents".equals(node)) { scriptMapping = new ArrayList<FxTypeScriptImportMapping>(5); while (reader.hasMoreChildren()) { reader.moveDown(); if (!"scriptMapping".equals(reader.getNodeName())) throw new FxConversionException("ex.conversion.wrongNode", "scriptMapping", reader.getNodeName()).asRuntimeException(); final Boolean derived = Boolean.valueOf(reader.getAttribute("derived")); scriptMapping .add(new FxTypeScriptImportMapping(FxScriptEvent.valueOf(reader.getAttribute("event")), reader.getAttribute("script"), Boolean.valueOf(reader.getAttribute("active")), Boolean.valueOf(reader.getAttribute("derivedUsage")), derived, derived ? reader.getAttribute("baseType") : "")); reader.moveUp(); } } else if ("assignments".equals(node)) { processAssignments = true; break; } if (!processAssignments) reader.moveUp(); } try { long typeId = typeEngine.save(typeEdit); //appy LifeCycleInfos Connection con = null; PreparedStatement ps = null; StringBuilder sql = new StringBuilder(500); try { con = Database.getDbConnection(); sql.append("UPDATE ").append(TBL_STRUCT_TYPES) .append(" SET CREATED_BY=?, CREATED_AT=?, MODIFIED_BY=?, MODIFIED_AT=? WHERE ID=?"); ps = con.prepareStatement(sql.toString()); ps.setLong(1, typeEdit.getLifeCycleInfo().getCreatorId()); ps.setLong(2, typeEdit.getLifeCycleInfo().getCreationTime()); ps.setLong(3, typeEdit.getLifeCycleInfo().getModificatorId()); ps.setLong(4, typeEdit.getLifeCycleInfo().getModificationTime()); ps.setLong(5, typeId); ps.executeUpdate(); StructureLoader.reload(con); } catch (Exception e) { throw new FxApplicationException(e, "ex.conversion.type.error", typeEdit.getName(), e.getMessage()) .asRuntimeException(); } finally { Database.closeObjects(FxTypeConverter.class, con, ps); } typeEdit = CacheAdmin.getEnvironment().getType(typeId).asEditable(); } catch (FxApplicationException e) { throw e.asRuntimeException(); } ctx.put(ConversionEngine.KEY_TYPE, typeEdit); try { //save and reload if (scriptMapping != null) { typeEdit = CacheAdmin.getEnvironment().getType(typeEngine.save(typeEdit)).asEditable(); final ScriptingEngine scriptingEngine = EJBLookup.getScriptingEngine(); //remove all script assignments final Set<FxScriptEvent> scriptEvents = new HashSet<FxScriptEvent>(typeEdit.getScriptEvents()); for (FxScriptEvent ev : scriptEvents) for (long scriptId : typeEdit.getScriptMapping(ev)) { scriptingEngine.removeTypeScriptMapping(scriptId, typeEdit.getId()); } //and re-add them for (FxTypeScriptImportMapping sm : scriptMapping) { try { scriptingEngine.createTypeScriptMapping(sm.getEvent(), env.getScript(sm.getScriptName()).getId(), typeEdit.getId(), sm.isActive(), sm.isDerivedUsage()); } catch (FxEntryExistsException e) { //mapping already exists via inheritance } } try { StructureLoader.reload(null); } catch (FxCacheException e) { throw new FxApplicationException(e, "ex.conversion.type.error", typeEdit.getName(), e.getMessage()).asRuntimeException(); } } } catch (FxApplicationException e) { throw e.asRuntimeException(); } if (processAssignments) { while (reader.hasMoreChildren() || (processAssignments && reader.hasMoreChildren())) { reader.moveDown(); String node = reader.getNodeName(); if (ConversionEngine.KEY_PROPERTY_AS.equals(node)) { ctx.convertAnother(this, FxPropertyAssignment.class); } else if (ConversionEngine.KEY_GROUP_AS.equals(node)) { ctx.convertAnother(this, FxGroupAssignment.class); } else throw new FxConversionException("ex.conversion.unexcpectedNode", reader.getNodeName()) .asRuntimeException(); reader.moveUp(); } reader.moveUp(); //move up the final assignments closing node } return typeEdit; }
From source file:com.mtgi.analytics.JdbcBehaviorEventPersisterImpl.java
public void persist(final Queue<BehaviorEvent> events) { getJdbcTemplate().execute(new ConnectionCallback() { public Object doInConnection(Connection con) throws SQLException, DataAccessException { //if this connection is behavior tracking, suspend tracking. //we don't generate more events while persisting. BehaviorTrackingConnectionProxy bt = null; for (Connection c = con; bt == null && c instanceof ConnectionProxy; c = ((ConnectionProxy) c).getTargetConnection()) { if (c instanceof BehaviorTrackingConnectionProxy) { bt = (BehaviorTrackingConnectionProxy) c; bt.suspendTracking(); }/*w w w . j av a2s .c o m*/ } try { boolean doBatch = supportsBatchUpdates(con); EventDataElementSerializer dataSerializer = new EventDataElementSerializer(xmlFactory); PreparedStatement[] idStmt = { null }; PreparedStatement insert = con.prepareStatement(insertSql); try { //keep track of statements added to the batch so that we can time our //flushes. int batchCount = 0; for (BehaviorEvent next : events) { //event may already have an ID assigned if any //of its child events has been persisted. assignIds(next, con, idStmt); //populate identifying information for the event into the insert statement. insert.setLong(1, (Long) next.getId()); BehaviorEvent parent = next.getParent(); nullSafeSet(insert, 2, parent == null ? null : parent.getId(), Types.BIGINT); insert.setString(3, next.getApplication()); insert.setString(4, next.getType()); insert.setString(5, next.getName()); insert.setTimestamp(6, new java.sql.Timestamp(next.getStart().getTime())); insert.setLong(7, next.getDurationNs()); //set optional context information on the event. nullSafeSet(insert, 8, next.getUserId(), Types.VARCHAR); nullSafeSet(insert, 9, next.getSessionId(), Types.VARCHAR); nullSafeSet(insert, 10, next.getError(), Types.VARCHAR); //convert event data to XML String data = dataSerializer.serialize(next.getData(), true); nullSafeSet(insert, 11, data, Types.VARCHAR); if (doBatch) { insert.addBatch(); if (++batchCount >= batchSize) { insert.executeBatch(); batchCount = 0; } } else { insert.executeUpdate(); } } //flush any lingering batch inserts through to the server. if (batchCount > 0) insert.executeBatch(); } finally { closeStatement(insert); closeStatement(idStmt[0]); } return null; } finally { if (bt != null) bt.resumeTracking(); } } }); }
From source file:lineage2.gameserver.model.entity.Hero.java
/** * Method insertHeroDiary.//from w ww . j a v a2 s . c om * @param charId int * @param action int * @param param int */ private void insertHeroDiary(int charId, int action, int param) { Connection con = null; PreparedStatement statement = null; try { con = DatabaseFactory.getInstance().getConnection(); statement = con .prepareStatement("INSERT INTO heroes_diary (charId, time, action, param) values(?,?,?,?)"); statement.setInt(1, charId); statement.setLong(2, System.currentTimeMillis()); statement.setInt(3, action); statement.setInt(4, param); statement.execute(); statement.close(); } catch (SQLException e) { _log.error("SQL exception while saving DiaryData.", e); } finally { DbUtils.closeQuietly(con, statement); } }