List of usage examples for java.sql PreparedStatement setNull
void setNull(int parameterIndex, int sqlType) throws SQLException;
NULL
. From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java
/** * Helper function to create a new node. * * @param con an open and valid connection * @param seq reference to a sequencer * @param ce reference to the content engine * @param mode Live or Edit mode * @param parentNodeId the parent node (1=root) * @param name the name of the new node (only informative value) * @param label label for Caption property (only used if new reference is created) * @param position the position within the childs (0 based, Integer.MAX_VALUE may be used to * append to the end) * @param reference a reference to an existing content (must exist!) * @param data the optional data * @param nodeId the id to use or create a new one if < 0 * @param activateContent change the step of contents that have no live step to live in the max version? * @return the used or created node id/*ww w.j a v a 2s . co m*/ * @throws FxTreeException if the function fails */ private long _createNode(Connection con, SequencerEngine seq, ContentEngine ce, FxTreeMode mode, long parentNodeId, String name, FxString label, int position, FxPK reference, String data, long nodeId, boolean activateContent) throws FxApplicationException { // acquire exclusive lock for parent node acquireLocksForUpdate(con, mode, Arrays.asList(parentNodeId)); // makeSpace(con, seq/*irrelevant*/, mode, parentNodeId, position/*irrelevant*/, 1); FxTreeNodeInfoSpreaded parentNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, parentNodeId); BigInteger boundaries[] = getBoundaries(con, parentNode, position); BigInteger leftBoundary = boundaries[0]; //== left border BigInteger rightBoundary = boundaries[1]; //== right border // Node has to be inserted between the left and right boundary and needs 2 slots for its left and right border BigInteger spacing = rightBoundary.subtract(leftBoundary).subtract(TWO); // Compute spacing for left,inner and right part spacing = spacing.divide(THREE); // We need at least 2 open slots (for the left and right boundary of the new node) //if the spacing is <= 0 we need more space if (spacing.compareTo(BigInteger.ZERO) <= 0/*less than*/) { throw new FxTreeException("ex.tree.create.noSpace", parentNodeId); } // try to use space more efficiently for flat structures, otherwise the first node of a folder // will get a third of the subtree space, the second one ninth, and so on. // Maxspacing indicates the number of nodes (*2) we expect to put in this node before space reorg spacing = spacing.compareTo(DEFAULT_NODE_SPACING) > 0 ? DEFAULT_NODE_SPACING : spacing; // final BigInteger left = leftBoundary.add(spacing).add(BigInteger.ONE); // don't add gap to left boundary (doesn't seem to have any benefits since that space is lost // unless the tree is reorganized anyway final BigInteger left = leftBoundary.add(BigInteger.ONE); final BigInteger right = left.add(spacing).add(BigInteger.ONE); NodeCreateInfo nci = getNodeCreateInfo(mode, seq, ce, nodeId, name, label, reference, activateContent); // Create the node PreparedStatement ps = null; try { ps = con.prepareStatement("INSERT INTO " + getTable(mode) + " (ID,PARENT,DEPTH,DIRTY,REF,LFT,RGT," + "CHILDCOUNT,NAME,MODIFIED_AT,TEMPLATE) VALUES " + "(" + nci.id + "," + parentNodeId + "," + (parentNode.getDepth() + 1) + ",?," + nci.reference.getId() + ",?,?,0,?," + StorageManager.getTimestampFunction() + ",?)"); ps.setBoolean(1, mode != FxTreeMode.Live); setNodeBounds(ps, 2, left); setNodeBounds(ps, 3, right); ps.setString(4, FxFormatUtils.escapeTreePath(nci.name)); if (StringUtils.isEmpty(data)) { ps.setNull(5, java.sql.Types.VARCHAR); } else { ps.setString(6, data); } ps.executeUpdate(); ps.close(); //update the parents childcount ps = con.prepareStatement( "UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + parentNodeId); ps.executeUpdate(); } catch (SQLException e) { throw new FxTreeException(LOG, e, "ex.db.sqlError", e.getMessage()); } finally { try { if (ps != null) ps.close(); } catch (Throwable t) { /*ignore*/ } } return nci.id; }
From source file:org.getobjects.eoaccess.EOAdaptorChannel.java
protected void _setStatementParameter(final PreparedStatement _stmt, final int _idx, final int _type, final Object _value) throws SQLException { if (_stmt == null) return;/* w w w.ja v a 2 s .co m*/ /* NULL */ if (_value == null) { _stmt.setNull(_idx, _type); return; } /* values */ switch (_type) { case java.sql.Types.NULL: _stmt.setNull(_idx, java.sql.Types.VARCHAR); // CRAP break; // TODO: customize value processing for types case java.sql.Types.VARCHAR: case java.sql.Types.TIMESTAMP: case java.sql.Types.DATE: case java.sql.Types.INTEGER: case java.sql.Types.BOOLEAN: default: if (_value instanceof String) _stmt.setString(_idx, (String) _value); else if (_value instanceof Boolean) _stmt.setBoolean(_idx, (Boolean) _value); else if (_value instanceof Integer) _stmt.setInt(_idx, (Integer) _value); else if (_value instanceof Long) _stmt.setLong(_idx, (Long) _value); else if (_value instanceof Double) _stmt.setDouble(_idx, (Double) _value); else if (_value instanceof BigDecimal) _stmt.setBigDecimal(_idx, (BigDecimal) _value); else if (_value instanceof java.util.Date) { _stmt.setTimestamp(_idx, new java.sql.Timestamp(((Date) _value).getTime())); } else if (_value instanceof java.sql.Date) { /* Note: this is just the DATE component, no TIME */ _stmt.setDate(_idx, (java.sql.Date) _value); } else if (_value instanceof java.util.Calendar) { // TBD: shouldn't we use setDate with a proper Calendar? final Date vd = ((Calendar) _value).getTime(); _stmt.setTimestamp(_idx, new java.sql.Timestamp(vd.getTime())); } else if (_value instanceof byte[]) _stmt.setBytes(_idx, (byte[]) _value); else { log.warn("using String column for value: " + _value + " (" + _value.getClass() + ")"); } } }
From source file:helma.objectmodel.db.NodeManager.java
private void setStatementValue(PreparedStatement stmt, int stmtNumber, Property p, int columnType) throws SQLException { if (p.getValue() == null) { stmt.setNull(stmtNumber, columnType); } else {//ww w . j av a2 s . co m switch (columnType) { case Types.BIT: case Types.BOOLEAN: stmt.setBoolean(stmtNumber, p.getBooleanValue()); break; case Types.TINYINT: case Types.BIGINT: case Types.SMALLINT: case Types.INTEGER: stmt.setLong(stmtNumber, p.getIntegerValue()); break; case Types.REAL: case Types.FLOAT: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: stmt.setDouble(stmtNumber, p.getFloatValue()); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: case Types.BLOB: Object b = p.getJavaObjectValue(); if (b instanceof byte[]) { byte[] buf = (byte[]) b; try { stmt.setBytes(stmtNumber, buf); } catch (SQLException x) { ByteArrayInputStream bout = new ByteArrayInputStream(buf); stmt.setBinaryStream(stmtNumber, bout, buf.length); } } else { throw new SQLException( "expected byte[] for binary column '" + p.getName() + "', found " + b.getClass()); } break; case Types.LONGVARCHAR: try { stmt.setString(stmtNumber, p.getStringValue()); } catch (SQLException x) { String str = p.getStringValue(); Reader r = new StringReader(str); stmt.setCharacterStream(stmtNumber, r, str.length()); } break; case Types.CLOB: String val = p.getStringValue(); Reader isr = new StringReader(val); stmt.setCharacterStream(stmtNumber, isr, val.length()); break; case Types.CHAR: case Types.VARCHAR: case Types.OTHER: stmt.setString(stmtNumber, p.getStringValue()); break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: stmt.setTimestamp(stmtNumber, p.getTimestampValue()); break; case Types.NULL: stmt.setNull(stmtNumber, 0); break; default: stmt.setString(stmtNumber, p.getStringValue()); break; } } }
From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java
/** * Description of the Method/*from www .j a va2 s. c om*/ * * @param db Description of Parameter * @return Description of the Returned Value * @throws SQLException Description of Exception */ public boolean insert(Connection db) throws SQLException { if (!isValid()) { LOG.debug("Object validation failed"); return false; } boolean result = false; boolean doCommit = false; try { if (doCommit = db.getAutoCommit()) { db.setAutoCommit(false); } StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO project_files " + "(folder_id, subject, client_filename, filename, version, size, "); sql.append("enabled, downloads, "); if (entered != null) { sql.append("entered, "); } if (modified != null) { sql.append("modified, "); } sql.append(" link_module_id, link_item_id, " + " enteredby, modifiedby, default_file, image_width, image_height, comment, featured_file) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, "); if (entered != null) { sql.append("?, "); } if (modified != null) { sql.append("?, "); } sql.append("?, ?, ?, ?, ?, ?, ?, ?, ?) "); int i = 0; PreparedStatement pst = db.prepareStatement(sql.toString()); if (folderId > 0) { pst.setInt(++i, folderId); } else { pst.setNull(++i, java.sql.Types.INTEGER); } pst.setString(++i, subject); pst.setString(++i, clientFilename); pst.setString(++i, filename); pst.setDouble(++i, version); pst.setInt(++i, size); pst.setBoolean(++i, enabled); pst.setInt(++i, downloads); if (entered != null) { pst.setTimestamp(++i, entered); } if (modified != null) { pst.setTimestamp(++i, modified); } pst.setInt(++i, linkModuleId); pst.setInt(++i, linkItemId); pst.setInt(++i, enteredBy); pst.setInt(++i, modifiedBy); pst.setBoolean(++i, defaultFile); pst.setInt(++i, imageWidth); pst.setInt(++i, imageHeight); pst.setString(++i, comment); pst.setBoolean(++i, featuredFile); pst.execute(); pst.close(); id = DatabaseUtils.getCurrVal(db, "project_files_item_id_seq", -1); // New default item if (defaultFile) { updateDefaultRecord(db, linkModuleId, linkItemId, id); } // Insert the version information if (doVersionInsert) { FileItemVersion thisVersion = new FileItemVersion(); thisVersion.setId(this.getId()); thisVersion.setSubject(subject); thisVersion.setClientFilename(clientFilename); thisVersion.setFilename(filename); thisVersion.setVersion(version); thisVersion.setSize(size); thisVersion.setEnteredBy(enteredBy); thisVersion.setModifiedBy(modifiedBy); thisVersion.setImageWidth(imageWidth); thisVersion.setImageHeight(imageHeight); thisVersion.setComment(comment); thisVersion.insert(db); } logUpload(db); if (doCommit) { db.commit(); } result = true; } catch (Exception e) { e.printStackTrace(System.out); if (doCommit) { db.rollback(); } throw new SQLException(e.getMessage()); } finally { if (doCommit) { db.setAutoCommit(true); } } return result; }
From source file:com.concursive.connect.web.modules.documents.dao.FileItem.java
/** * Description of the Method/*from w w w . j a v a 2 s .co m*/ * * @param db Description of the Parameter * @param newFolderId Description of the Parameter * @throws SQLException Description of the Exception */ public void updateFolderId(Connection db, int newFolderId) throws SQLException { if (id == -1) { throw new SQLException("ID not specified"); } PreparedStatement pst = db .prepareStatement("UPDATE project_files " + "SET folder_id = ? " + "WHERE item_id = ?"); int i = 0; if (newFolderId > 0) { pst.setInt(++i, newFolderId); } else { pst.setNull(++i, java.sql.Types.INTEGER); } pst.setInt(++i, id); int count = pst.executeUpdate(); pst.close(); if (count == 1) { if (newFolderId > 0) { folderId = newFolderId; } else { folderId = -1; } } }
From source file:org.jobjects.dao.annotation.Manager.java
/** * Retourne le bean partir de la clef primaire. Si la ligne n'existe pas * dans la base alors une exception FinderException est leve. * @param beanPk Le bean d'un type quelconque comportant des annotations daoTable et * DaoField. Il represente la clef primaire de la table. * @return Un bean de mme type que celui pass en paramtre. Les donnes du * bean sont rafraichi partir de la base au cas o celle-ci aurait * modifi les donnes grace des trigger ou autre. * @throws FinderException Returne un exception si le bean n'existe pas. *//* ww w . j av a2 s. co m*/ public final T load(final P beanPk) throws FinderException { T returnValue = null; try { String msg = "Load error " + entityClass.getCanonicalName() + " : " + ToStringBuilder.reflectionToString(beanPk, ToStringStyle.MULTI_LINE_STYLE); try { Connection connection = getConnection(); try { if (null == sql_load) { sql_load = loadSqlLoad(usualTable, fields); } PreparedStatement pstmt = connection.prepareStatement(sql_load); try { int i = 1; for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { if (((DaoField) annotation).isPrimary()) { Object obj = BeanUtils.getProperty(beanPk, field.getName()); if (obj == null) { pstmt.setNull(i++, ((DaoField) annotation).type()); } else { setAll(pstmt, i++, obj); } } break; } } } ResultSet rs = pstmt.executeQuery(); try { if (!rs.next()) { throw new FinderException(msg); } returnValue = entityClass.newInstance(); int j = 1; for (Field field : fields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof DaoField) { // field.set(returnValue, // rs.getObject(j++)); BeanUtils.setProperty(returnValue, field.getName(), rs.getObject(j++)); break; } } } } finally { rs.close(); } rs = null; } finally { pstmt.close(); } pstmt = null; } finally { connection.close(); } connection = null; } catch (SQLException sqle) { log.error(msg, sqle); throw new FinderException(msg, sqle); } } catch (Exception e) { throw new FinderException(e); } return returnValue; }
From source file:ca.nrc.cadc.uws.server.JobDAO.java
private int setString(PreparedStatement ps, int col, String tableName, String columnName, String value, StringBuilder sb) throws SQLException { Integer limit = jobSchema.getColumnLength(tableName, columnName); if (limit == null) { // single column if (value == null) ps.setNull(col, Types.VARCHAR); else/*from w w w . ja v a2 s. c om*/ ps.setString(col, value); sb.append(value); sb.append(","); return 1; } // pair of columns if (value == null) { ps.setNull(col, Types.VARCHAR); ps.setNull(col + 1, Types.VARCHAR); sb.append("null,null,"); } else if (value.length() <= limit) { ps.setString(col, value); ps.setNull(col + 1, Types.VARCHAR); sb.append(value); sb.append(",null,"); } else { ps.setNull(col, Types.VARCHAR); ps.setString(col + 1, value); sb.append("null,"); sb.append(value); sb.append(","); } return 2; }
From source file:migration.ProjektMigration.java
/** * Creates the rechnung./*w ww . ja v a2s .com*/ */ public void createRechnung() { String load_sql; Statement load_stmt; ResultSet load_rs; String store_sql; PreparedStatement store_prepstmt; final ResultSet store_rs; try { load_sql = "SELECT Rechnungsbetrag, Bezugsform, Bezugsjahr, Sigel, Exemplar, ExImportID FROM ExRechnungstabelle"; load_stmt = this.leg_con.createStatement(); store_sql = "insert into Rechnung (betrag, bezugsform, bezugsjahr, exemplar_exemplarId) values (?, ?, ?, ?)";// , // sigel_sigelId store_prepstmt = this.tgt_con.prepareStatement(store_sql); // evtl. // brauchen // wir // was // in // Richtung: // Statement.RETURN_GENERATED_KEYS // logger.info("Lese von ExRechnungstabelle"); load_stmt.execute(load_sql); load_rs = load_stmt.getResultSet(); // logger.info("Schreibe nach Rechnung"); while (load_rs.next()) { store_prepstmt.setInt(1, load_rs.getInt("Rechnungsbetrag")); store_prepstmt.setString(2, load_rs.getString("Bezugsform")); store_prepstmt.setString(3, load_rs.getString("Bezugsjahr")); int tmp = this.help.getIdFromIntArray(this.getExemplare(), load_rs.getInt("Exemplar")); if (tmp > 0) { store_prepstmt.setLong(4, tmp); } else { store_prepstmt.setNull(4, java.sql.Types.BIGINT); } tmp = this.help.getIdFromStringArray(this.help.getSigel(), load_rs.getString("Sigel")); // store_prepstmt.setLong(5, (long)tmp); store_prepstmt.executeUpdate(); } } catch (final SQLException e) { e.printStackTrace(); // To change body of catch statement use File | // Settings | File Templates. } // insert into Interesse (besteller_bestellerId, interesse, journal_id) // values (?, ?, ?) // insert into Nutzung (journal_id, nutzungsjahr, rechnungsbetrag, // zeitraum, zugriffe) values (?, ?, ?, ?, ?) // insert into Rechnung (betrag, bezugsform, bezugsjahr, // exemplar_exemplarId, sigel_sigelId) values (?, ?, ?, ?, ?) }
From source file:architecture.common.adaptor.connector.jdbc.AbstractJdbcConnector.java
/** * Batch .../*from ww w . ja v a 2s . c om*/ * * @param queryString * @param parameterMappings * @param rows * @return */ protected Object deliver(final String queryString, final List<ParameterMapping> parameterMappings, final List<Map<String, Object>> rows) { log.debug("delivering : " + rows.size()); int[] cnt = getJdbcTemplate().batchUpdate(queryString, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { Map<String, Object> row = rows.get(i); for (ParameterMapping mapping : parameterMappings) { JdbcType jdbcType = mapping.getJdbcType(); Object value = row.get(mapping.getProperty()); Object valueToUse = value; if (valueToUse == null && mapping.getJavaType() == Date.class) { valueToUse = new Date(); } if (valueToUse instanceof Date && jdbcType == JdbcType.VARCHAR) { valueToUse = DateFormatUtils.format((Date) valueToUse, mapping.getPattern()); } if (valueToUse instanceof String && jdbcType == JdbcType.VARCHAR) { String stringValue = (String) valueToUse; if (!StringUtils.isEmpty(mapping.getEncoding())) { if (!StringUtils.isEmpty(stringValue)) { String[] encoding = StringUtils.split(mapping.getEncoding(), ">"); try { if (encoding.length == 2) valueToUse = new String(stringValue.getBytes(encoding[0]), encoding[1]); else if (encoding.length == 1) valueToUse = new String(stringValue.getBytes(), encoding[0]); } catch (UnsupportedEncodingException e) { LOG.error(e); } } } } if (valueToUse == null) ps.setNull(mapping.getIndex(), jdbcType.TYPE_CODE); else ps.setObject(mapping.getIndex(), valueToUse, jdbcType.TYPE_CODE); } } public int getBatchSize() { return rows.size(); } }); int sum = 0; for (int c : cnt) { sum = sum + c; } return sum; }
From source file:com.flexive.ejb.beans.BriefcaseEngineBean.java
/** * {@inheritDoc}//from w ww .j av a 2 s . c o m */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public long create(String name, String description, Long aclId, LifeCycleInfo forcedLifeCycleInfo) throws FxApplicationException { final UserTicket ticket = FxContext.getUserTicket(); if (description == null) { description = ""; } if (name == null || name.trim().length() == 0) { throw new FxInvalidParameterException("ex.briefcase.nameMissing", "name"); } if (aclId != null && aclId != -1) { ACL acl; try { acl = new ACLEngineBean().load(aclId); } catch (Throwable t) { throw new FxInvalidParameterException("ex.briefcase.invalidAcl", "acl"); } if (!ticket.mayCreateACL(aclId, ticket.getUserId())) { throw new FxNoAccessException("ex.briefcase.noCreatePermission", acl.getLabel()); } } if (forcedLifeCycleInfo != null && !ticket.isGlobalSupervisor()) { throw new FxNoAccessException("ex.briefcase.lciPermission"); } Connection con = null; PreparedStatement ps = null; String sql; String sourceQuery = ""; try { // Obtain a database connection con = Database.getDbConnection(); // Obtain a new id long newId = seq.getId(FxSystemSequencer.BRIEFCASE); sql = "INSERT INTO " + DatabaseConst.TBL_BRIEFCASE + "(" + //1, 2, 3 , 4 , 5 , 6 7 8 9 , 10 , 11 "ID,NAME,DESCRIPTION,SOURCE_QUERY,ACL,CREATED_BY,CREATED_AT,MODIFIED_BY,MODIFIED_AT,MANDATOR,ICON_ID)" + "VALUES (?,?,?,?,?,?,?,?,?,?,1)"; final long NOW = System.currentTimeMillis(); ps = con.prepareStatement(sql); ps.setLong(1, newId); ps.setString(2, name); ps.setString(3, description); ps.setString(4, sourceQuery); if (aclId != null && aclId != -1) { ps.setLong(5, aclId); } else { ps.setNull(5, java.sql.Types.NUMERIC); } if (forcedLifeCycleInfo != null) { ps.setLong(6, forcedLifeCycleInfo.getCreatorId()); ps.setLong(7, forcedLifeCycleInfo.getCreationTime()); ps.setLong(8, forcedLifeCycleInfo.getModificatorId()); ps.setLong(9, forcedLifeCycleInfo.getModificationTime()); } else { ps.setLong(6, ticket.getUserId()); ps.setLong(7, NOW); ps.setLong(8, ticket.getUserId()); ps.setLong(9, NOW); } ps.setLong(10, ticket.getMandatorId()); ps.executeUpdate(); return newId; } catch (SQLException exc) { final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc); if (ctx != null) { EJBUtils.rollback(ctx); } else { try { if (con != null) con.rollback(); } catch (SQLException e) { LOG.warn(e.getMessage(), e); } } if (uniqueConstraintViolation) { throw new FxEntryExistsException(LOG, "ex.briefcase.nameAlreadyExists", name); } else { throw new FxCreateException(LOG, exc, "ex.briefcase.createFailed"); } } finally { closeObjects(BriefcaseEngineBean.class, con, ps); } }