List of usage examples for java.sql PreparedStatement setNull
void setNull(int parameterIndex, int sqlType) throws SQLException;
NULL
. From source file:org.obm.domain.dao.ContactDaoJdbcImpl.java
@Override @AutoTruncate/* ww w.j a v a2 s . c o m*/ public Contact updateContact(AccessToken token, @DatabaseEntity Contact contact) throws SQLException, FindException, EventNotFoundException, ServerFault { String q = "UPDATE Contact SET " + "contact_commonname=?, contact_firstname=?, " + "contact_lastname=?, contact_origin=?, contact_userupdate=?, " + "contact_aka=?, contact_title=?, contact_service=?, contact_company=?, contact_comment=?, " + "contact_suffix=?, contact_manager=?, contact_middlename=?, contact_assistant=?, contact_spouse=?, contact_anniversary_id=?, contact_birthday_id=? " + "WHERE contact_id=? "; logger.info("update contact with id=" + contact.getUid() + " entityId=" + contact.getEntityId()); Connection con = null; PreparedStatement ps = null; try { con = obmHelper.getConnection(); EventObmId anniversaryId = createOrUpdateDate(token, con, contact, contact.getAnniversary(), ANNIVERSARY_FIELD); contact.setAnniversaryId(anniversaryId); EventObmId birthdayId = createOrUpdateDate(token, con, contact, contact.getBirthday(), BIRTHDAY_FIELD); contact.setBirthdayId(birthdayId); ps = con.prepareStatement(q); int idx = 1; ps.setString(idx++, contact.getCommonname()); ps.setString(idx++, contact.getFirstname()); ps.setString(idx++, contact.getLastname()); ps.setString(idx++, token.getOrigin()); ps.setInt(idx++, token.getObmId()); ps.setString(idx++, contact.getAka()); ps.setString(idx++, contact.getTitle()); ps.setString(idx++, contact.getService()); ps.setString(idx++, contact.getCompany()); ps.setString(idx++, contact.getComment()); ps.setString(idx++, contact.getSuffix()); ps.setString(idx++, contact.getManager()); ps.setString(idx++, contact.getMiddlename()); ps.setString(idx++, contact.getAssistant()); ps.setString(idx++, contact.getSpouse()); if (contact.getAnniversaryId() == null) { ps.setNull(idx++, Types.INTEGER); } else { ps.setInt(idx++, contact.getAnniversaryId().getObmId()); } if (contact.getBirthdayId() == null) { ps.setNull(idx++, Types.INTEGER); } else { ps.setInt(idx++, contact.getBirthdayId().getObmId()); } ps.setInt(idx++, contact.getUid()); ps.executeUpdate(); removeAndCreateAddresses(con, contact.getEntityId(), contact.getAddresses()); removeAndCreateEmails(con, contact.getEntityId(), contact.getEmails()); removeAndCreatePhones(con, contact.getEntityId(), contact.getPhones()); removeAndCreateWebsites(con, contact); removeAndCreateIMIdentifiers(con, contact.getEntityId(), contact.getImIdentifiers()); } finally { obmHelper.cleanup(con, ps, null); } entityDaoListener.contactHasBeenCreated(token, contact); return contact; }
From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java
/** * Save given inputs to the database./*from w ww.ja v a 2 s . c o m*/ * * Use given prepare statement to save all inputs into repository. * * @param config * corresponding config * @param inputs * List of inputs that needs to be saved * @param baseInputStmt * Statement that we can utilize * @throws java.sql.SQLException * In case of any failure on Derby side */ private void registerConfigInputs(MConfig config, List<MInput<?>> inputs, PreparedStatement baseInputStmt) throws SQLException { short inputIndex = 0; for (MInput<?> input : inputs) { baseInputStmt.setString(1, input.getName()); baseInputStmt.setLong(2, config.getPersistenceId()); baseInputStmt.setShort(3, inputIndex++); baseInputStmt.setString(4, input.getType().name()); baseInputStmt.setBoolean(5, input.isSensitive()); // String specific column(s) if (input.getType().equals(MInputType.STRING)) { MStringInput strInput = (MStringInput) input; baseInputStmt.setShort(6, strInput.getMaxLength()); } else { baseInputStmt.setNull(6, Types.INTEGER); } baseInputStmt.setString(7, input.getEditable().name()); // Enum specific column(s) if (input.getType() == MInputType.ENUM) { baseInputStmt.setString(8, StringUtils.join(((MEnumInput) input).getValues(), ",")); } else { baseInputStmt.setNull(8, Types.VARCHAR); } int baseInputCount = baseInputStmt.executeUpdate(); if (baseInputCount != 1) { throw new SqoopException(CommonRepositoryError.COMMON_0014, Integer.toString(baseInputCount)); } ResultSet rsetInputId = baseInputStmt.getGeneratedKeys(); if (!rsetInputId.next()) { throw new SqoopException(CommonRepositoryError.COMMON_0015); } long inputId = rsetInputId.getLong(1); input.setPersistenceId(inputId); } }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.JDBCConnector.java
/** * This method executes a low level insert with the data values * and data types (java.sql.Types) specified in a Map. * This is a way to improve the performance of data insertion. * * @param sql escaped SQL to avoid SQL-I * @param line the line to inser//from w w w . j a v a2s . c o m * @param columns of the table * @return number of affected rows * @throws Exception exception thrown */ public int executeLineInsertLowLevel(String sql, String[] line, List<ColumnVO> columns) throws Exception { Exception error = null; int numRowsAffected = 0; if (columns.size() > 0) { Connection connection = null; PreparedStatement preparedStmnt = null; try { DataSource dataSource = poolDataSources.get(schemaId); connection = dataSource.getConnection(); connection.setAutoCommit(false); preparedStmnt = connection.prepareStatement(sql); String coordinateX = null; String coordinateY = null; int paramPosition = 1; for (ColumnVO column : columns) { Integer filePosition = column.getFilePosition(); String dataValue; Integer dataType = column.getSqlType(); if (column.isCoordinateX()) { dataValue = line[filePosition]; coordinateX = dataValue; preparedStmnt.setObject(paramPosition, dataValue, dataType); } else if (column.isCoordinateY()) { dataValue = line[filePosition]; coordinateY = dataValue; preparedStmnt.setObject(paramPosition, dataValue, dataType); } else if (column.isFromCoordinates()) { int coordXIndex = column.getFileCoordinateXPosition(); int coordYIndex = column.getFileCoordinateYPosition(); coordinateX = line[coordXIndex]; coordinateY = line[coordYIndex]; continue; } else if (dataType == Types.OTHER) { // it is a geometry // ((org.postgresql.PGConnection)connection).addDataType(column.getName(), // column.getTypeClass()); dataValue = line[filePosition]; preparedStmnt.setObject(paramPosition, dataValue); } else { dataValue = line[filePosition]; if (StringUtils.isEmpty(dataValue)) { preparedStmnt.setNull(paramPosition, dataType); } else { preparedStmnt.setObject(paramPosition, dataValue, dataType); } } paramPosition++; } if ((coordinateX != null) && (coordinateY != null)) { String pointWKT = Utils.getPointWKTFromCoordinates(coordinateX, coordinateY); preparedStmnt.setObject(paramPosition, pointWKT); } numRowsAffected = preparedStmnt.executeUpdate(); connection.commit(); } catch (SQLException e) { error = e; } finally { if (preparedStmnt != null) { try { preparedStmnt.close(); } catch (SQLException se2) { log.warn("No se pudo cerrar el statment: ".concat(se2.getLocalizedMessage())); } } if (connection != null) { try { if (error != null) { connection.rollback(); } } catch (SQLException se) { log.warn("Se produjo un error al manejar la conexin: ".concat(se.getLocalizedMessage())); } try { connection.close(); } catch (SQLException se) { log.warn("Se produjo un error al intentar cerrar la conexin: " .concat(se.getLocalizedMessage())); } } } if (error != null) { throw error; } } return numRowsAffected; }
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void insert(final Ligplaats ligplaats) throws DAOException { try {/*from ww w. ja v a2s . co m*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection .prepareStatement("insert into bag_ligplaats (" + "bag_ligplaats_id," + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "officieel," + "ligplaats_status," + "ligplaats_geometrie," + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer," + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setLong(1, ligplaats.getIdentificatie()); ps.setInt(2, ligplaats.getAanduidingRecordInactief().ordinal()); ps.setLong(3, ligplaats.getAanduidingRecordCorrectie()); ps.setInt(4, ligplaats.getOfficieel().ordinal()); ps.setInt(5, ligplaats.getLigplaatsStatus().ordinal()); ps.setString(6, ligplaats.getLigplaatsGeometrie()); ps.setTimestamp(7, new Timestamp(ligplaats.getBegindatumTijdvakGeldigheid().getTime())); if (ligplaats.getEinddatumTijdvakGeldigheid() == null) ps.setNull(8, Types.TIMESTAMP); else ps.setTimestamp(8, new Timestamp(ligplaats.getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(9, ligplaats.getInOnderzoek().ordinal()); ps.setDate(10, new Date(ligplaats.getDocumentdatum().getTime())); ps.setString(11, ligplaats.getDocumentnummer()); ps.setLong(12, ligplaats.getHoofdAdres()); return ps; } }); insertNevenadressen(TypeAdresseerbaarObject.LIGPLAATS, ligplaats); } }); } catch (DataAccessException e) { throw new DAOException("Error inserting ligplaats: " + ligplaats.getIdentificatie(), e); } }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * Create an HDFS connection ( used only in version 2). * Intended to be used when moving HDFS connector out of the sqoop driver * to its own connector.//from w w w .ja v a 2s .c o m * * NOTE: Should be used only in the upgrade path! */ @Deprecated private Long createHdfsConnection(Connection conn, Long connectorId) { if (LOG.isTraceEnabled()) { LOG.trace("Creating HDFS link."); } PreparedStatement stmt = null; int result; try { stmt = conn.prepareStatement(STMT_INSERT_CONNECTION, Statement.RETURN_GENERATED_KEYS); stmt.setString(1, CONNECTOR_HDFS); stmt.setLong(2, connectorId); stmt.setBoolean(3, true); stmt.setNull(4, Types.VARCHAR); stmt.setTimestamp(5, new Timestamp(System.currentTimeMillis())); stmt.setNull(6, Types.VARCHAR); stmt.setTimestamp(7, new Timestamp(System.currentTimeMillis())); result = stmt.executeUpdate(); if (result != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0003, Integer.toString(result)); } ResultSet rsetConnectionId = stmt.getGeneratedKeys(); if (!rsetConnectionId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0004); } if (LOG.isTraceEnabled()) { LOG.trace("Created HDFS connection."); } return rsetConnectionId.getLong(1); } catch (SQLException ex) { throw new SqoopException(DerbyRepoError.DERBYREPO_0005, ex); } finally { closeStatements(stmt); } }
From source file:org.methodize.nntprss.feed.db.JdbcChannelDAO.java
public void updateChannel(Channel channel) { Connection conn = null;/*ww w .j a v a2 s. co m*/ PreparedStatement ps = null; try { conn = DriverManager.getConnection(JdbcChannelDAO.POOL_CONNECT_STRING); ps = conn.prepareStatement("UPDATE " + TABLE_CHANNELS + " " + "SET author = ?, name = ?, url = ?, " + "title = ?, link = ?, description = ?, " + "lastArticle = ?, " + "lastPolled = ?, lastCleaned = ?, lastModified = ?, lastETag = ?, rssVersion = ?, " + "enabled = ?, " + "postingEnabled = ?, " + "publishAPI = ?, " + "publishConfig = ?, " + "parseAtAllCost = ?, " + "managingEditor = ?, " + "pollingInterval = ?, " + "status = ?, " + "expiration = ?, " + "category = ? " + "WHERE id = ?"); int paramCount = 1; ps.setString(paramCount++, trim(channel.getAuthor(), FIELD_CHANNEL_AUTHOR_LENGTH)); ps.setString(paramCount++, trim(channel.getName(), FIELD_CHANNEL_NAME_LENGTH)); ps.setString(paramCount++, channel.getUrl()); ps.setString(paramCount++, trim(channel.getTitle(), FIELD_CHANNEL_TITLE_LENGTH)); ps.setString(paramCount++, channel.getLink()); ps.setString(paramCount++, channel.getDescription()); ps.setInt(paramCount++, channel.getLastArticleNumber()); if (channel.getLastPolled() != null) { ps.setTimestamp(paramCount++, new Timestamp(channel.getLastPolled().getTime())); } else { ps.setNull(paramCount++, java.sql.Types.TIMESTAMP); } if (channel.getLastCleaned() != null) { ps.setTimestamp(paramCount++, new Timestamp(channel.getLastCleaned().getTime())); } else { ps.setNull(paramCount++, java.sql.Types.TIMESTAMP); } ps.setLong(paramCount++, channel.getLastModified()); ps.setString(paramCount++, channel.getLastETag()); ps.setString(paramCount++, trim(channel.getRssVersion(), FIELD_CHANNEL_VERSION_LENGTH)); // ps.setBoolean(paramCount++, channel.isHistorical()); ps.setBoolean(paramCount++, channel.isEnabled()); ps.setBoolean(paramCount++, channel.isPostingEnabled()); ps.setString(paramCount++, channel.getPublishAPI()); ps.setString(paramCount++, XMLHelper.stringMapToXML(channel.getPublishConfig())); ps.setBoolean(paramCount++, channel.isParseAtAllCost()); ps.setString(paramCount++, trim(channel.getManagingEditor(), FIELD_CHANNEL_MANAGING_EDITOR_LENGTH)); ps.setLong(paramCount++, channel.getPollingIntervalSeconds()); ps.setInt(paramCount++, channel.getStatus()); ps.setLong(paramCount++, channel.getExpiration()); int categoryId = 0; if (channel.getCategory() != null) { categoryId = channel.getCategory().getId(); } ps.setInt(paramCount++, categoryId); ps.setInt(paramCount++, channel.getId()); ps.executeUpdate(); } catch (SQLException se) { throw new RuntimeException(se); } finally { try { if (ps != null) ps.close(); } catch (SQLException se) { } try { if (conn != null) conn.close(); } catch (SQLException se) { } } }
From source file:fr.aliacom.obm.common.contact.ContactDaoJdbcImpl.java
private int insertIntoContact(Connection con, AccessToken at, Contact c, int addressBookId) throws SQLException { PreparedStatement ps = null; try {/*from www . ja va2 s .c om*/ ps = con.prepareStatement("INSERT INTO Contact " + " (contact_commonname, contact_firstname, contact_lastname, contact_origin, contact_domain_id, contact_usercreate, " + "contact_company, contact_aka, contact_service, contact_title, contact_birthday_id, contact_anniversary_id, " + "contact_timecreate, " + "contact_suffix, contact_middlename, contact_manager, contact_spouse, contact_assistant, " + "contact_collected, contact_addressbook_id) " + " VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now(), ?, ?, ?, ?, ?, ?, ?) "); int idx = 1; ps.setString(idx++, c.getCommonname()); ps.setString(idx++, c.getFirstname()); ps.setString(idx++, c.getLastname()); ps.setString(idx++, at.getOrigin()); ps.setInt(idx++, at.getDomain().getId()); ps.setInt(idx++, at.getObmId()); ps.setString(idx++, c.getCompany()); ps.setString(idx++, c.getAka()); ps.setString(idx++, c.getService()); ps.setString(idx++, c.getTitle()); if (c.getBirthdayId() != null) { ps.setInt(idx++, c.getBirthdayId().getObmId()); } else { ps.setNull(idx++, Types.BIGINT); } if (c.getAnniversaryId() != null) { ps.setInt(idx++, c.getAnniversaryId().getObmId()); } else { ps.setNull(idx++, Types.BIGINT); } ps.setString(idx++, c.getSuffix()); ps.setString(idx++, c.getMiddlename()); ps.setString(idx++, c.getManager()); ps.setString(idx++, c.getSpouse()); ps.setString(idx++, c.getAssistant()); ps.setBoolean(idx++, c.isCollected()); ps.setInt(idx++, addressBookId); ps.executeUpdate(); int contactId = obmHelper.lastInsertId(con); return contactId; } finally { obmHelper.cleanup(null, ps, null); } }
From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java
private int fillEventStatement(PreparedStatement ps, Event ev, AccessToken at, int i) throws SQLException { int idx = i;/* w w w. jav a2s.c o m*/ ps.setString(idx++, ev.getExtId().getExtId()); ps.setString(idx++, ev.getTimezoneName()); ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VOPACITY, ev.getOpacity().toString())); ps.setString(idx++, ev.getTitle()); ps.setString(idx++, ev.getLocation()); Integer cat = catIdFromString(ps.getConnection(), ev.getCategory(), at.getDomain().getId()); if (cat != null) { ps.setInt(idx++, cat); } else { ps.setNull(idx++, Types.INTEGER); } ps.setInt(idx++, RFC2445.getPriorityOrDefault(ev.getPriority())); ps.setInt(idx++, ev.getPrivacy().toInteger()); if (ev.getStartDate() != null) { ps.setTimestamp(idx++, new Timestamp(ev.getStartDate().getTime())); } else { ps.setNull(idx++, Types.DATE); } ps.setInt(idx++, ev.getDuration()); ps.setBoolean(idx++, ev.isAllday()); EventRecurrence r = ev.getRecurrence(); ps.setString(idx++, r.getKind().toString()); ps.setInt(idx++, r.getFrequence()); ps.setString(idx++, new RecurrenceDaysSerializer().serialize(r.getDays())); if (r.getEnd() != null) { ps.setTimestamp(idx++, new Timestamp(r.getEnd().getTime())); } else { ps.setNull(idx++, Types.DATE); } ps.setNull(idx++, Types.VARCHAR); // color ps.setNull(idx++, Types.DATE); // FIXME completed ps.setNull(idx++, Types.VARCHAR); // FIXME url ps.setString(idx++, ev.getDescription()); ps.setInt(idx++, at.getDomain().getId()); ps.setString(idx++, at.getOrigin()); ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VCOMPONENT, ev.getType().toString())); ps.setInt(idx++, ev.getSequence()); return idx; }
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void insert(final Standplaats standplaats) throws DAOException { try {//from ww w. ja v a 2 s .c o m transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection .prepareStatement("insert into bag_standplaats (" + "bag_standplaats_id," + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "officieel," + "standplaats_status," + "standplaats_geometrie," + "begindatum_tijdvak_geldigheid," + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "bron_documentdatum," + "bron_documentnummer," + "bag_nummeraanduiding_id" + ") values (?,?,?,?,?,?,?,?,?,?,?,?)"); ps.setLong(1, standplaats.getIdentificatie()); ps.setInt(2, standplaats.getAanduidingRecordInactief().ordinal()); ps.setLong(3, standplaats.getAanduidingRecordCorrectie()); ps.setInt(4, standplaats.getOfficieel().ordinal()); ps.setInt(5, standplaats.getStandplaatsStatus().ordinal()); ps.setString(6, standplaats.getStandplaatsGeometrie()); ps.setTimestamp(7, new Timestamp(standplaats.getBegindatumTijdvakGeldigheid().getTime())); if (standplaats.getEinddatumTijdvakGeldigheid() == null) ps.setNull(8, Types.TIMESTAMP); else ps.setTimestamp(8, new Timestamp(standplaats.getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(9, standplaats.getInOnderzoek().ordinal()); ps.setDate(10, new Date(standplaats.getDocumentdatum().getTime())); ps.setString(11, standplaats.getDocumentnummer()); ps.setLong(12, standplaats.getHoofdAdres()); return ps; } }); insertNevenadressen(TypeAdresseerbaarObject.STANDPLAATS, standplaats); } }); } catch (DataAccessException e) { throw new DAOException("Error inserting standplaats: " + standplaats.getIdentificatie(), e); } }
From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java
@Override public void update(final Verblijfsobject origineel, final Verblijfsobject mutation) throws DAOException { try {/*from w w w . j a v a 2s .c om*/ transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement("update bag_verblijfsobject set" + " aanduiding_record_inactief = ?," + " aanduiding_record_correctie = ?," + " officieel = ?," + " verblijfsobject_geometrie = ?," + " oppervlakte_verblijfsobject = ?," + " verblijfsobject_status = ?," + " einddatum_tijdvak_geldigheid = ?," + " in_onderzoek = ?," + " bron_documentdatum = ?," + " bron_documentnummer = ?," + " bag_nummeraanduiding_id = ?" + " where bag_verblijfsobject_id = ?" + " and aanduiding_record_correctie = ?" + " and begindatum_tijdvak_geldigheid = ?"); ps.setInt(1, mutation.getAanduidingRecordInactief().ordinal()); ps.setLong(2, mutation.getAanduidingRecordCorrectie()); ps.setInt(3, mutation.getOfficieel().ordinal()); ps.setString(4, mutation.getVerblijfsobjectGeometrie()); ps.setInt(5, mutation.getOppervlakteVerblijfsobject()); ps.setInt(6, mutation.getVerblijfsobjectStatus().ordinal()); if (mutation.getEinddatumTijdvakGeldigheid() == null) ps.setNull(7, Types.TIMESTAMP); else ps.setTimestamp(7, new Timestamp(mutation.getEinddatumTijdvakGeldigheid().getTime())); ps.setInt(8, mutation.getInOnderzoek().ordinal()); ps.setDate(9, new Date(mutation.getDocumentdatum().getTime())); ps.setString(10, mutation.getDocumentnummer()); ps.setLong(11, mutation.getHoofdAdres()); ps.setLong(12, origineel.getIdentificatie()); ps.setLong(13, origineel.getAanduidingRecordCorrectie()); ps.setTimestamp(14, new Timestamp(origineel.getBegindatumTijdvakGeldigheid().getTime())); return ps; } }); deleteGebruikersdoelen(origineel); insertGebruikersdoelen(mutation); deleteNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, origineel); insertNevenadressen(TypeAdresseerbaarObject.VERBLIJFSOBJECT, mutation); deleteGerelateerdePanden(origineel); insertGerelateerdePanden(mutation); } }); } catch (DataAccessException e) { throw new DAOException("Error updating verblijfsobject: " + origineel.getIdentificatie(), e); } }