List of usage examples for java.sql PreparedStatement setNull
void setNull(int parameterIndex, int sqlType) throws SQLException;
NULL
. From source file:com.flexive.ejb.beans.LanguageBean.java
/** * {@inheritDoc}//from w w w. jav a 2s . c om */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void setAvailable(List<FxLanguage> available, boolean ignoreUsage) throws FxApplicationException { FxPermissionUtils.checkRole(FxContext.getUserTicket(), Role.GlobalSupervisor); Connection con = null; PreparedStatement ps = null; if (available == null || available.size() == 0) throw new FxInvalidParameterException("available", "ex.language.noAvailable"); try { con = Database.getDbConnection(); if (!ignoreUsage) { List<FxLanguage> orgLang = loadAvailable(true); boolean found; for (FxLanguage org : orgLang) { found = false; for (FxLanguage tmp : available) { if (tmp.getId() == org.getId()) { found = true; break; } } if (!found && hasUsages(con, org)) throw new FxInvalidParameterException("available", "ex.language.removeUsed", org.getLabel()); } } ps = con.prepareStatement("UPDATE " + TBL_LANG + " SET INUSE=?, DISPPOS=?"); ps.setBoolean(1, false); ps.setNull(2, java.sql.Types.INTEGER); ps.executeUpdate(); ps.close(); int pos = 0; ps = con.prepareStatement("UPDATE " + TBL_LANG + " SET INUSE=?, DISPPOS=? WHERE LANG_CODE=?"); ps.setBoolean(1, true); for (FxLanguage lang : available) { ps.setInt(2, pos++); ps.setLong(3, lang.getId()); ps.addBatch(); } ps.executeBatch(); StructureLoader.updateLanguages(FxContext.get().getDivisionId(), loadAll(true, true)); } catch (FxCacheException e) { LOG.error(e, e); } catch (SQLException e) { throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { Database.closeObjects(LanguageBean.class, con, ps); } }
From source file:com.flexive.ejb.beans.structure.SelectListEngineBean.java
/** * Update an existing item//from w ww . j a v a 2 s .com * * @param item the item to update * @throws FxApplicationException on errors */ private void updateItem(FxSelectListItemEdit item) throws FxApplicationException { if (!item.changes()) return; checkValidItemParameters(item); // System.out.println("Updating item " + item.getLabel()); if (!(FxContext.getUserTicket().isInRole(Role.SelectListEditor) || FxContext.getUserTicket() .mayEditACL(item.getAcl().getId(), FxContext.getUserTicket().getUserId()))) throw new FxNoAccessException("ex.selectlist.item.update.noPerm", item.getList().getLabel(), item.getAcl().getLabel()); Connection con = null; PreparedStatement ps = null; try { con = Database.getDbConnection(); // 1 2 3 4 5 ps = con.prepareStatement( "UPDATE " + TBL_STRUCT_SELECTLIST_ITEM + " SET NAME=?, ACL=?,PARENTID=?,DATA=?,COLOR=?," + // 6 7 8 9 10 11 "MODIFIED_BY=?,MODIFIED_AT=?,DBIN_ID=?,DBIN_VER=?,DBIN_QUALITY=? WHERE ID=?"); ps.setString(1, item.getName()); ps.setLong(2, item.getAcl().getId()); if (item.hasParentItem()) ps.setLong(3, item.getParentItem().getId()); else ps.setNull(3, java.sql.Types.INTEGER); ps.setString(4, item.getData()); ps.setString(5, item.getColor()); LifeCycleInfoImpl.updateLifeCycleInfo(ps, 6, 7); ps.setLong(8, item.getIconId()); ps.setInt(9, item.getIconVer()); ps.setInt(10, item.getIconQuality()); ps.setLong(11, item.getId()); ps.executeUpdate(); Database.storeFxString(item.getLabel(), con, TBL_STRUCT_SELECTLIST_ITEM, "LABEL", "ID", item.getId()); } catch (SQLException e) { try { if (StorageManager.isUniqueConstraintViolation(e)) throw new FxUpdateException(LOG, e, "ex.selectlist.item.name.notUnique", item.getName()); throw new FxUpdateException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { EJBUtils.rollback(ctx); } } finally { Database.closeObjects(TypeEngineBean.class, con, ps); } }
From source file:com.archivas.clienttools.arcutils.utils.database.PopulateDmDb.java
private void insertRows() throws SQLException, DatabaseException, JobException { ArcMoverEngine engine = LocalJvmArcMoverEngine.getInstance(); List<ManagedJobSummary> allJobs = engine.getAllManagedJobs(); JobId jobId = null;/*from w ww . j a v a 2 s.c o m*/ for (ManagedJobSummary summary : allJobs) { if (summary.getJobName().equals(jobName)) { jobId = summary.getJobId(); break; } } if (jobId == null) { throw new IllegalArgumentException("Job \"" + jobName + "\" not found"); } System.out.print("Loading managed job ...."); System.out.flush(); ManagedJobImpl jobImpl = engine.loadManagedJob(jobId, jobType); System.out.println(" done"); ManagedJob job = jobImpl.getJob(); AbstractProfileBase sourceProfile = job.getSourceProfile(); AbstractProfileBase targetProfile = job.getTargetProfile(); String sourcePath = job.getSourcePath(); String targetPath = job.getTargetPath(); ArcCopyFile file = generateFile(sourceProfile, targetProfile, sourcePath, targetPath); String fileSourcePath = file.getSourcePath(); String fileSourceProfile = file.getSourceProfile().getName(); String fileTargetPath = file.getTargetPath(); String fileTargetProfile = (targetProfile == null ? null : file.getTargetProfile().getName()); long fileSize = file.getSize(); int fileObjectType = FileType.UNKNOWN.ordinal(); if (file.isDirectory()) { fileObjectType = FileType.DIRECTORY.ordinal(); } else if (file.isFile()) { fileObjectType = FileType.FILE.ordinal(); } Long version = file.getSourceVersion(); if (version == null) { version = 0L; } long recordId = jobImpl.getManagedJobSchema().getLastDbRecordId(); long discoveredObjectCnt = jobImpl.getDiscoveredObjectCount(); long totalObjCnt = jobImpl.getTotalObjectCount(); System.out.println( "*** max RECORD_ID = " + recordId + ", initialDiscoveredObjectCnt = " + discoveredObjectCnt); boolean isDelete = (jobType == ManagedJob.Type.DELETE); String insertSql = "INSERT INTO " + ManagedJobSchema.getJobSchemaName(jobId.getId()) + "." + ManagedJobSchema.JOB_FILES_TABLE_NAME + (isDelete ? DELETE_INSERT_COLS_SQL : COPY_INSERT_COLS_SQL); String updateSql = "UPDATE " + ManagedJobsSchema.JOBS_TABLE_NAME + " set " + ManagedJobTableColumn.DISCOVERED_OBJ_CNT + " = ?, " + // 1 ManagedJobTableColumn.MAX_RECORD_ID + " = ?, " + // 2 ManagedJobTableColumn.TOTAL_OBJ_CNT + " = ? " + // 3 " WHERE " + ManagedJobTableColumn.JOB_ID + " = ?"; // 4 Connection conn = DatabaseResourceManager.createConnection(); conn.setAutoCommit(false); PreparedStatement insertStatement = conn.prepareStatement(insertSql); PreparedStatement updateStatement = conn.prepareStatement(updateSql); startTime = System.currentTimeMillis(); long l = 0; for (; l < rowCnt; l++) { recordId++; getLifeCycle(l); if (fileLifeCycle.ordinal() > FileLifeCycle.FINDING.ordinal()) { totalObjCnt++; } discoveredObjectCnt++; insertStatement.clearParameters(); insertStatement.setInt(1, DatabaseResourceManager.boolToDbValue(false)); // initial list insertStatement.setLong(2, recordId); // record id insertStatement.setInt(3, fileObjectType); // record type insertStatement.setString(4, fileSourcePath); // source path insertStatement.setLong(5, version); // source version insertStatement.setString(6, fileSourceProfile); // source profile name insertStatement.setInt(7, fileLifeCycle.ordinal()); // life cycle if (fileStatus == null) { insertStatement.setNull(8, java.sql.Types.SMALLINT); // status } else { insertStatement.setInt(8, fileStatus.ordinal()); } if (!isDelete) { insertStatement.setString(9, fileTargetPath); // target path insertStatement.setString(10, fileTargetProfile); // target profile name insertStatement.setLong(11, fileSize); // size } insertStatement.execute(); if (l % 5000 == 0) { // update counts in jobs table updateStatement.clearParameters(); updateStatement.setLong(1, discoveredObjectCnt); updateStatement.setLong(2, recordId); updateStatement.setLong(3, totalObjCnt); updateStatement.setLong(4, jobId.getId()); updateStatement.execute(); conn.commit(); displayStats(l); } } updateStatement.clearParameters(); updateStatement.setLong(1, discoveredObjectCnt); updateStatement.setLong(2, recordId); updateStatement.setLong(3, totalObjCnt); updateStatement.setLong(4, jobId.getId()); updateStatement.execute(); conn.commit(); displayStats(l); }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.H2Engine.java
@Override protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps, final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException { int i = 1;/*from ww w . j av a 2 s. co m*/ for (DbColumn column : entity.getColumns()) { if ((column.isAutoInc() && useAutoInc)) { continue; } try { final Object val; if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) { val = column.getDefaultValue().getConstant(); } else { val = entry.get(column.getName()); } switch (column.getDbColumnType()) { case BLOB: ps.setBytes(i, objectToArray(val)); break; case CLOB: if (val == null) { ps.setNull(i, Types.CLOB); break; } if (val instanceof String) { StringReader sr = new StringReader((String) val); ps.setCharacterStream(i, sr); } else { throw new DatabaseEngineException("Cannot convert " + val.getClass().getSimpleName() + " to String. CLOB columns only accept Strings."); } break; default: ps.setObject(i, val); } } catch (Exception ex) { throw new DatabaseEngineException("Error while mapping variables to database", ex); } i++; } return i - 1; }
From source file:com.act.lcms.db.model.StandardIonResult.java
protected void bindInsertOrUpdateParameters(PreparedStatement stmt, String chemical, Integer standardWellId, List<Integer> negativeWellIds, LinkedHashMap<String, XZ> analysisResults, Map<String, String> plottingResultFileMapping, String bestMetlinIon, Integer manualOverrideId) throws SQLException, IOException { stmt.setString(DB_FIELD.CHEMICAL.getInsertUpdateOffset(), chemical); stmt.setInt(DB_FIELD.STANDARD_WELL_ID.getInsertUpdateOffset(), standardWellId); stmt.setString(DB_FIELD.NEGATIVE_WELL_IDS.getInsertUpdateOffset(), OBJECT_MAPPER.writeValueAsString(negativeWellIds)); stmt.setString(DB_FIELD.PLOTTING_RESULT_PATHS.getInsertUpdateOffset(), serializePlottingPaths(plottingResultFileMapping)); stmt.setString(DB_FIELD.STANDARD_ION_RESULTS.getInsertUpdateOffset(), serializeStandardIonAnalysisResult(analysisResults)); stmt.setString(DB_FIELD.BEST_METLIN_ION.getInsertUpdateOffset(), bestMetlinIon); if (manualOverrideId == null) { stmt.setNull(DB_FIELD.MANUAL_OVERRIDE.getInsertUpdateOffset(), Types.INTEGER); } else {//from w w w. j a v a 2 s . c om stmt.setInt(DB_FIELD.MANUAL_OVERRIDE.getInsertUpdateOffset(), manualOverrideId); } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.PostgreSqlEngine.java
@Override protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps, final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException { int i = 1;//from w w w .j a va 2s.c o m for (DbColumn column : entity.getColumns()) { if (column.isAutoInc() && useAutoInc) { continue; } try { final Object val; if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) { val = column.getDefaultValue().getConstant(); } else { val = entry.get(column.getName()); } switch (column.getDbColumnType()) { case BLOB: ps.setBytes(i, objectToArray(val)); break; case CLOB: if (val == null) { ps.setNull(i, Types.CLOB); break; } if (val instanceof String) { //StringReader sr = new StringReader((String) val); //ps.setClob(i, sr); // postrgresql driver des not have setClob implemented ps.setString(i, (String) val); } else { throw new DatabaseEngineException("Cannot convert " + val.getClass().getSimpleName() + " to String. CLOB columns only accept Strings."); } break; default: ps.setObject(i, val); } } catch (Exception ex) { throw new DatabaseEngineException("Error while mapping variables to database", ex); } i++; } return i - 1; }
From source file:org.linqs.psl.database.rdbms.RDBMSInserter.java
private void insertInternal(List<Double> values, List<List<Object>> data) { assert (values.size() == data.size()); int partitionID = partition.getID(); if (partitionID < 0) { throw new IllegalArgumentException("Partition IDs must be non-negative."); }/*from www . j a v a2s . co m*/ for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) { List<Object> row = data.get(rowIndex); assert (row != null); if (row.size() != predicateInfo.argumentColumns().size()) { throw new IllegalArgumentException( String.format("Data on row %d length does not match for %s: Expecting: %d, Got: %d", rowIndex, partition.getName(), predicateInfo.argumentColumns().size(), row.size())); } } try (Connection connection = dataStore.getConnection(); PreparedStatement multiInsertStatement = connection.prepareStatement(multiInsertSQL); PreparedStatement singleInsertStatement = connection.prepareStatement(singleInsertSQL);) { int batchSize = 0; // We will go from the multi-insert to the single-insert when we don't have enough data to fill the multi-insert. PreparedStatement activeStatement = multiInsertStatement; int insertSize = DEFAULT_MULTIROW_COUNT; int rowIndex = 0; while (rowIndex < data.size()) { // Index for the current index. int paramIndex = 1; if (activeStatement == multiInsertStatement && data.size() - rowIndex < DEFAULT_MULTIROW_COUNT) { // Commit any records left in the multi-insert batch. if (batchSize > 0) { activeStatement.executeBatch(); activeStatement.clearBatch(); batchSize = 0; } activeStatement = singleInsertStatement; insertSize = 1; } for (int i = 0; i < insertSize; i++) { List<Object> row = data.get(rowIndex); Double value = values.get(rowIndex); // Partition activeStatement.setInt(paramIndex++, partitionID); // Value if (value == null || value.isNaN()) { activeStatement.setNull(paramIndex++, java.sql.Types.DOUBLE); } else { activeStatement.setDouble(paramIndex++, value); } for (int argIndex = 0; argIndex < predicateInfo.argumentColumns().size(); argIndex++) { Object argValue = row.get(argIndex); assert (argValue != null); if (argValue instanceof Integer) { activeStatement.setInt(paramIndex++, (Integer) argValue); } else if (argValue instanceof Double) { // The standard JDBC way to insert NaN is using setNull if (Double.isNaN((Double) argValue)) { activeStatement.setNull(paramIndex++, java.sql.Types.DOUBLE); } else { activeStatement.setDouble(paramIndex++, (Double) argValue); } } else if (argValue instanceof String) { // This is the most common value we get when someone is using InsertUtils. // The value may need to be convered from a string. activeStatement.setObject(paramIndex++, convertString((String) argValue, argIndex)); } else if (argValue instanceof UniqueIntID) { activeStatement.setInt(paramIndex++, ((UniqueIntID) argValue).getID()); } else if (argValue instanceof UniqueStringID) { activeStatement.setString(paramIndex++, ((UniqueStringID) argValue).getID()); } else { throw new IllegalArgumentException("Unknown data type for :" + argValue); } } rowIndex++; } activeStatement.addBatch(); batchSize++; if (batchSize >= DEFAULT_PAGE_SIZE) { activeStatement.executeBatch(); activeStatement.clearBatch(); batchSize = 0; } } if (batchSize > 0) { activeStatement.executeBatch(); activeStatement.clearBatch(); batchSize = 0; } activeStatement.clearParameters(); activeStatement = null; } catch (SQLException ex) { log.error(ex.getMessage()); throw new RuntimeException("Error inserting into RDBMS.", ex); } }
From source file:com.wso2telco.dep.ratecardservice.dao.RateCategoryDAO.java
public RateCategoryDTO addRateCategory(RateCategoryDTO rateCategory) throws BusinessException { Connection con = null;//from w w w . j a v a2s . c om PreparedStatement ps = null; ResultSet rs = null; Integer rateCategoryId = 0; try { con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB); if (con == null) { log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection"); throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED); } StringBuilder query = new StringBuilder("insert into "); query.append(DatabaseTables.RATE_CATEGORY.getTObject()); query.append(" (rate_defid, parentcategoryid, childcategoryid, tariffid, createdby)"); query.append(" values"); query.append(" (?, ?, ?, ?, ?)"); ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); log.debug("sql query in addRateCategory : " + ps); ps.setInt(1, rateCategory.getRateDefinition().getRateDefId()); ps.setInt(2, rateCategory.getCategory().getCategoryId()); Integer subCategoryId = rateCategory.getSubCategory().getCategoryId(); if (subCategoryId != null) { ps.setInt(3, subCategoryId); } else { ps.setNull(3, Types.INTEGER); } ps.setInt(4, rateCategory.getTariff().getTariffId()); ps.setString(5, rateCategory.getCreatedBy()); ps.executeUpdate(); rs = ps.getGeneratedKeys(); while (rs.next()) { rateCategoryId = rs.getInt(1); } rateCategory.setRateCategoryId(rateCategoryId); } catch (SQLException e) { log.error("database operation error in addRateCategory : ", e); throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED); } catch (Exception e) { log.error("error in addRateCategory : ", e); throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED); } finally { DbUtils.closeAllConnections(ps, con, rs); } return rateCategory; }
From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java
/** * {@inheritDoc}/*from ww w.j a v a 2 s . c om*/ */ @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public void track(FxType type, FxPK pk, String data, String key, Object... args) { Connection con = null; PreparedStatement ps = null; try { final UserTicket ticket = FxContext.getUserTicket(); con = Database.getDbConnection(); ps = con.prepareStatement(StorageManager.escapeReservedWords(HISTORY_INSERT)); ps.setLong(1, ticket.getUserId()); ps.setString(2, ticket.getLoginName()); ps.setLong(3, System.currentTimeMillis()); ps.setString(4, key); StorageManager.setBigString(ps, 5, StringUtils.join(args, '|')); try { ps.setString(6, FxSharedUtils.getLocalizedMessage("History", FxLanguage.ENGLISH, "en", key, args)); } catch (Exception e) { ps.setString(6, key); } FxContext si = FxContext.get(); ps.setString(7, (si.getSessionId() == null ? "<unknown>" : si.getSessionId())); ps.setString(8, (si.getApplicationId() == null ? "<unknown>" : si.getApplicationId())); ps.setString(9, (si.getRemoteHost() == null ? "<unknown>" : si.getRemoteHost())); if (type != null) { ps.setLong(10, type.getId()); ps.setString(11, type.getName()); } else { ps.setNull(10, java.sql.Types.NUMERIC); ps.setNull(11, java.sql.Types.VARCHAR); } if (pk != null) { ps.setLong(12, pk.getId()); ps.setInt(13, pk.getVersion()); } else { ps.setNull(12, java.sql.Types.NUMERIC); ps.setNull(13, java.sql.Types.NUMERIC); } if (data != null) StorageManager.setBigString(ps, 14, data); else ps.setNull(14, java.sql.Types.VARCHAR); ps.executeUpdate(); } catch (Exception ex) { LOG.error(ex.getMessage()); } finally { Database.closeObjects(HistoryTrackerEngineBean.class, con, ps); } }
From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java
public int storeData(DataList list) { try {//from w ww .j a v a 2s .c o m Connection conn = dataSourceWrite.getConnection(); if (conn != null) { int i; DataItem item; EventItem event; Object tag; conn.setAutoCommit(false); PreparedStatement stmt; Date t1 = new Date(); stmt = conn.prepareStatement(sqlInsertStmt); for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) { if (!(item instanceof EventItem)) continue; event = (EventItem) item; ValueItem val = event.getValue(); tag = this.getTagOfDp(event.getDp()); if (tag == null) continue; if (tag instanceof Long) stmt.setLong(1, (Long) tag); else if (tag instanceof String) stmt.setString(1, (String) tag); java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS()); ts.setNanos(event.getNanos()); stmt.setTimestamp(2, ts, cal); Double dval = val.getDouble(); if (dval != null) { stmt.setDouble(3, dval); } else { stmt.setNull(3, Types.DOUBLE); } // value_string stmt.setString(4, val.getString()); // value_timestamp if (val.getTimeMS() != null) stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal); else stmt.setNull(5, Types.TIMESTAMP); // status, manager, user if (event.hasAttributes()) { stmt.setLong(6, event.getStatus()); stmt.setInt(7, event.getManager()); stmt.setInt(8, event.getUser()); } else { stmt.setNull(6, Types.INTEGER); stmt.setNull(7, Types.INTEGER); stmt.setNull(8, Types.INTEGER); } //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()}); stmt.addBatch(); } try { stmt.executeBatch(); // TODO check result? int[] res = } catch (BatchUpdateException ex) { JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.", new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length }); JDebug.StackTrace(Level.SEVERE, ex); } catch (SQLException ex) { SQLException current = ex; do { JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() }); JDebug.StackTrace(Level.SEVERE, current); } while ((current = current.getNextException()) != null); // for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) { // JDebug.out.log(Level.INFO, "{0}", item.toJSONObject()); // } } Date t2 = new Date(); stmt.close(); afterInsert(conn); conn.commit(); conn.close(); addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime()); return INoSQLInterface.OK; } else { JDebug.StackTrace(Level.SEVERE, "no connection!"); return INoSQLInterface.ERR_REPEATABLE; } } catch (Exception ex) { JDebug.StackTrace(Level.SEVERE, ex); return INoSQLInterface.ERR_REPEATABLE; } }