List of usage examples for java.sql Statement RETURN_GENERATED_KEYS
int RETURN_GENERATED_KEYS
To view the source code for java.sql Statement RETURN_GENERATED_KEYS.
Click Source Link
From source file:nz.co.gregs.dbvolution.actions.DBInsert.java
@Override protected DBActionList execute(DBDatabase db) throws SQLException { final DBDefinition defn = db.getDefinition(); DBRow row = getRow();//w ww.j a va2 s. co m DBActionList actions = new DBActionList(new DBInsert(row)); DBStatement statement = db.getDBStatement(); try { for (String sql : getSQLStatements(db)) { if (defn.supportsGeneratedKeys()) { try { String primaryKeyColumnName = row.getPrimaryKeyColumnName(); Integer pkIndex = row.getPrimaryKeyIndex(); if (pkIndex == null || primaryKeyColumnName == null) { statement.execute(sql); } else { if (primaryKeyColumnName.isEmpty()) { statement.execute(sql, Statement.RETURN_GENERATED_KEYS); } else { statement.execute(sql, new String[] { db.getDefinition() .formatPrimaryKeyForRetrievingGeneratedKeys(primaryKeyColumnName) }); pkIndex = 1; } if (row.getPrimaryKey().hasBeenSet() == false) { ResultSet generatedKeysResultSet = statement.getGeneratedKeys(); try { while (generatedKeysResultSet.next()) { final long pkValue = generatedKeysResultSet.getLong(pkIndex); if (pkValue > 0) { this.getGeneratedPrimaryKeys().add(pkValue); QueryableDatatype pkQDT = this.originalRow.getPrimaryKey(); new InternalQueryableDatatypeProxy(pkQDT).setValue(pkValue); pkQDT = row.getPrimaryKey(); new InternalQueryableDatatypeProxy(pkQDT).setValue(pkValue); } } } catch (SQLException ex) { throw new RuntimeException(ex); } finally { generatedKeysResultSet.close(); } } } } catch (SQLException sqlex) { try { sqlex.printStackTrace(); statement.execute(sql); } catch (SQLException ex) { throw new RuntimeException(sql, ex); } } } else { try { statement.execute(sql); final QueryableDatatype primaryKey = row.getPrimaryKey(); if (primaryKey != null && primaryKey.hasBeenSet() == false && defn.supportsRetrievingLastInsertedRowViaSQL()) { String retrieveSQL = defn.getRetrieveLastInsertedRowSQL(); ResultSet rs = statement.executeQuery(retrieveSQL); try { QueryableDatatype originalPK = this.originalRow.getPrimaryKey(); QueryableDatatype rowPK = row.getPrimaryKey(); if ((originalPK instanceof DBInteger) && (rowPK instanceof DBInteger)) { DBInteger inPK = (DBInteger) originalPK; DBInteger inRowPK = (DBInteger) rowPK; inPK.setValue(rs.getLong(1)); inRowPK.setValue(rs.getLong(1)); } else if ((originalPK instanceof DBNumber) && (rowPK instanceof DBInteger)) { DBNumber inPK = (DBNumber) originalPK; inPK.setValue(rs.getBigDecimal(1)); ((DBInteger) rowPK).setValue(rs.getLong(1)); } else if ((originalPK instanceof DBString) && (rowPK instanceof DBString)) { DBString inPK = (DBString) originalPK; inPK.setValue(rs.getString(1)); inPK = (DBString) rowPK; inPK.setValue(rs.getString(1)); } } finally { rs.close(); } } } catch (SQLException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } } } finally { statement.close(); } DBInsertLargeObjects blobSave = new DBInsertLargeObjects(this.originalRow); actions.addAll(blobSave.execute(db)); row.setDefined(); return actions; }
From source file:net.bhira.sample.api.dao.CompanyDaoImpl.java
/** * @see net.bhira.sample.api.dao.CompanyDao#save(net.bhira.sample.model.Company) *///from w w w.ja va 2 s . c o m @Override public void save(Company company) throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException { if (company == null) { throw new InvalidObjectException("Company object is null."); } company.initForSave(); company.validate(); boolean isNew = company.isNew(); int count = 0; if (isNew) { // for new company, construct SQL insert statement KeyHolder keyHolder = new GeneratedKeyHolder(); count = jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, company.getName()); pstmt.setString(2, company.getIndustry()); pstmt.setString(3, company.getBillingAddress()); pstmt.setString(4, company.getShippingAddress()); pstmt.setTimestamp(5, new Timestamp(company.getCreated().getTime())); pstmt.setTimestamp(6, new Timestamp(company.getModified().getTime())); pstmt.setString(7, company.getCreatedBy()); pstmt.setString(8, company.getModifiedBy()); return pstmt; } }, keyHolder); // fetch the newly created auto-increment ID company.setId(keyHolder.getKey().longValue()); LOG.debug("inserted company, count = {}, id = {}", count, company.getId()); } else { // for existing company, construct SQL update statement Object[] args = new Object[] { company.getName(), company.getIndustry(), company.getBillingAddress(), company.getShippingAddress(), company.getModified(), company.getModifiedBy(), company.getId() }; count = jdbcTemplate.update(SQL_UPDATE, args); LOG.debug("updated company, count = {}, id = {}", count, company.getId()); } // if insert/update has 0 count value, then throw exception if (count <= 0) { throw new ObjectNotFoundException("Company with ID " + company.getId() + " was not found."); } // update dependent entries, as needed if (isNew) { // for new model if there is contact info, save it to contact info table and then // add entry in relationship table if (company.getContactInfo() != null) { contactInfoDao.save(company.getContactInfo()); Object[] args = new Object[] { company.getId(), company.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } else { // for existing model, fetch contact info ID from relationship table List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class, new Object[] { company.getId() }); Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null; if (company.getContactInfo() == null) { // clean up old contact info entry, if needed if (cinfoId != null) { jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { company.getId() }); contactInfoDao.delete(cinfoId); } } else { // insert/update contact info entry if (cinfoId != null) { company.getContactInfo().setId(cinfoId); contactInfoDao.save(company.getContactInfo()); } else { contactInfoDao.save(company.getContactInfo()); Object[] args = new Object[] { company.getId(), company.getContactInfo().getId() }; jdbcTemplate.update(SQL_CINFO_REL_INSERT, args); } } } }
From source file:com.hortonworks.registries.storage.impl.jdbc.provider.sql.statement.PreparedStatementBuilder.java
/** Creates the prepared statement with the parameters in place to be replaced */ private void setPreparedStatement(boolean returnGeneratedKeys) throws SQLException { final String parameterizedSql = sqlBuilder.getParametrizedSql(); log.debug("Creating prepared statement for parameterized sql [{}]", parameterizedSql); final PreparedStatement preparedStatement; if (returnGeneratedKeys) { preparedStatement = connection.prepareStatement(parameterizedSql, Statement.RETURN_GENERATED_KEYS); } else {/*from w w w . j a va 2 s. c o m*/ preparedStatement = connection.prepareStatement(parameterizedSql); } final int queryTimeoutSecs = config.getQueryTimeoutSecs(); if (queryTimeoutSecs > 0) { preparedStatement.setQueryTimeout(queryTimeoutSecs); } this.preparedStatement = preparedStatement; }
From source file:com.javacodegags.waterflooding.model.CriteriaImplemented.java
@Override public int insertCriteria(int id) { final String sql = "INSERT INTO criteria (foreign_to_therm,formula,weight_factor,criteria_value) VALUES (" + id + ",'','0.1','0.1');"; KeyHolder holder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override/*from w w w. j a v a 2 s. c o m*/ public PreparedStatement createPreparedStatement(Connection cnctn) throws SQLException { PreparedStatement ps = cnctn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); return ps; } }, holder); this.setDefaultParams(holder.getKey().intValue()); return holder.getKey().intValue(); }
From source file:com.wso2telco.dep.ratecardservice.dao.TariffDAO.java
public TariffDTO addTariff(TariffDTO tariff) throws BusinessException { Connection con = null;/*from w w w. j a va 2s. co m*/ PreparedStatement ps = null; ResultSet rs = null; Integer tariffId = 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.TARIFF.getTObject()); query.append( " (tariffname, tariffdesc, tariffdefaultval, tariffmaxcount, tariffexcessrate, tariffdefrate, tariffspcommission, tariffadscommission, tariffopcocommission, tariffsurchargeval, tariffsurchargeAds, tariffsurchargeOpco, createdby)"); query.append(" values"); query.append(" (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); log.debug("sql query in addTariff : " + ps); ps.setString(1, tariff.getTariffName()); ps.setString(2, tariff.getTariffDescription()); Double tariffDefaultVal = tariff.getTariffDefaultVal(); if (tariffDefaultVal != null) { ps.setDouble(3, tariffDefaultVal); } else { ps.setNull(3, Types.DOUBLE); } Integer tariffMaxCount = tariff.getTariffMaxCount(); if (tariffMaxCount != null) { ps.setInt(4, tariffMaxCount); } else { ps.setNull(4, Types.INTEGER); } Double tariffExcessRate = tariff.getTariffExcessRate(); if (tariffExcessRate != null) { ps.setDouble(5, tariffExcessRate); } else { ps.setNull(5, Types.DOUBLE); } Double tariffDefRate = tariff.getTariffDefRate(); if (tariffDefRate != null) { ps.setDouble(6, tariffDefRate); } else { ps.setNull(6, Types.DOUBLE); } Double tariffSPCommission = tariff.getTariffSPCommission(); if (tariffSPCommission != null) { ps.setDouble(7, tariffSPCommission); } else { ps.setNull(7, Types.DOUBLE); } Double tariffAdsCommission = tariff.getTariffAdsCommission(); if (tariffAdsCommission != null) { ps.setDouble(8, tariffAdsCommission); } else { ps.setNull(8, Types.DOUBLE); } Double tariffOpcoCommission = tariff.getTariffOpcoCommission(); if (tariffOpcoCommission != null) { ps.setDouble(9, tariffOpcoCommission); } else { ps.setNull(9, Types.DOUBLE); } Double tariffSurChargeval = tariff.getTariffSurChargeval(); if (tariffSurChargeval != null) { ps.setDouble(10, tariffSurChargeval); } else { ps.setNull(10, Types.DOUBLE); } Double tariffSurChargeAds = tariff.getTariffSurChargeAds(); if (tariffSurChargeAds != null) { ps.setDouble(11, tariffSurChargeAds); } else { ps.setNull(11, Types.DOUBLE); } Double tariffSurChargeOpco = tariff.getTariffSurChargeOpco(); if (tariffSurChargeOpco != null) { ps.setDouble(12, tariffSurChargeOpco); } else { ps.setNull(12, Types.DOUBLE); } ps.setString(13, tariff.getCreatedBy()); ps.executeUpdate(); rs = ps.getGeneratedKeys(); while (rs.next()) { tariffId = rs.getInt(1); } tariff.setTariffId(tariffId); } catch (SQLException e) { log.error("database operation error in addTariff : ", e); throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED); } catch (Exception e) { log.error("error in addTariff : ", e); throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED); } finally { DbUtils.closeAllConnections(ps, con, rs); } return tariff; }
From source file:org.wso2.carbon.identity.authorization.core.jdbc.dao.JDBCModuleDAO.java
@Override protected void insert(PreparedStatement stmt, ResultSet res, Connection connection) throws SQLException, UserStoreException { String sql = "INSERT INTO UM_MODULE (UM_MODULE_NAME) VALUES(?) "; stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); byte count = 0; stmt.setString(++count, getModuleName()); int resCount = stmt.executeUpdate(); if (resCount == 0) { String error = "Insertion faild for the module " + getModuleName(); log.error(error);//from w ww. j a v a2s.c om throw new UserStoreException(error); } res = stmt.getGeneratedKeys(); if (res.next()) { setModuleId(res.getInt(1)); } }
From source file:com.mfast.evaluations.DCAppSession.java
private int putSkeletonInDB(int measurementFrameId, Skeleton sk) throws Exception { int skeletonId = 0; StringBuilder sq = new StringBuilder("INSERT INTO Skeleton "); sq.append("(measurementFrameId, skeletonSequenceNumber, "); sq.append("headX, headY, headZ, "); sq.append("hipCenterX, hipCenterY, hipCenterZ, "); sq.append("leftAnkleX, leftAnkleY, leftAnkleZ, "); sq.append("rightAnkleX, rightAnkleY, rightAnkleZ, "); sq.append("leftElbowX, leftElbowY, leftElbowZ, "); sq.append("rightElbowX, rightElbowY, rightElbowZ, "); sq.append("leftFootX, leftFootY, leftFootZ, "); sq.append("rightFootX, rightFootY, rightFootZ, "); sq.append("leftHandX, leftHandY, leftHandZ, "); sq.append("rightHandX, rightHandY, rightHandZ, "); sq.append("leftHipX, leftHipY, leftHipZ, "); sq.append("rightHipX, rightHipY, rightHipZ, "); sq.append("leftKneeX, leftKneeY, leftKneeZ, "); sq.append("rightKneeX, rightKneeY, rightKneeZ, "); sq.append("leftShoulderX, leftShoulderY, leftShoulderZ, "); sq.append("rightShoulderX, rightShoulderY, rightShoulderZ, "); sq.append("leftWristX, leftWristY, leftWristZ, "); sq.append("rightWristX, rightWristY, rightWristZ, "); sq.append("shoulderCenterX, shoulderCenterY, shoulderCenterZ, "); sq.append("spineX, spineY, spineZ) "); // 62 values//from w ww . j a v a 2 s . com sq.append( "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"); st = conn.prepareStatement(sq.toString(), Statement.RETURN_GENERATED_KEYS); st.setInt(1, measurementFrameId); st.setInt(2, sk.getId()); st.setDouble(3, sk.getHead()[0]); st.setDouble(4, sk.getHead()[1]); st.setDouble(5, sk.getHead()[2]); st.setDouble(6, sk.getHipCenter()[0]); st.setDouble(7, sk.getHipCenter()[1]); st.setDouble(8, sk.getHipCenter()[2]); st.setDouble(9, sk.getLeftAnkle()[0]); st.setDouble(10, sk.getLeftAnkle()[1]); st.setDouble(11, sk.getLeftAnkle()[2]); st.setDouble(12, sk.getRightAnkle()[0]); st.setDouble(13, sk.getRightAnkle()[1]); st.setDouble(14, sk.getRightAnkle()[2]); st.setDouble(15, sk.getLeftElbow()[0]); st.setDouble(16, sk.getLeftElbow()[1]); st.setDouble(17, sk.getLeftElbow()[2]); st.setDouble(18, sk.getRightElbow()[0]); st.setDouble(19, sk.getRightElbow()[1]); st.setDouble(20, sk.getRightElbow()[2]); st.setDouble(21, sk.getLeftFoot()[0]); st.setDouble(22, sk.getLeftFoot()[1]); st.setDouble(23, sk.getLeftFoot()[2]); st.setDouble(24, sk.getRightFoot()[0]); st.setDouble(25, sk.getRightFoot()[1]); st.setDouble(26, sk.getRightFoot()[2]); st.setDouble(27, sk.getLeftHand()[0]); st.setDouble(28, sk.getLeftHand()[1]); st.setDouble(29, sk.getLeftHand()[2]); st.setDouble(30, sk.getRightHand()[0]); st.setDouble(31, sk.getRightHand()[1]); st.setDouble(32, sk.getRightHand()[2]); st.setDouble(33, sk.getLeftHip()[0]); st.setDouble(34, sk.getLeftHip()[1]); st.setDouble(35, sk.getLeftHip()[2]); st.setDouble(36, sk.getRightHip()[0]); st.setDouble(37, sk.getRightHip()[1]); st.setDouble(38, sk.getRightHip()[2]); st.setDouble(39, sk.getLeftKnee()[0]); st.setDouble(40, sk.getLeftKnee()[1]); st.setDouble(41, sk.getLeftKnee()[2]); st.setDouble(42, sk.getRightKnee()[0]); st.setDouble(43, sk.getRightKnee()[1]); st.setDouble(44, sk.getRightKnee()[2]); st.setDouble(45, sk.getLeftShoulder()[0]); st.setDouble(46, sk.getLeftShoulder()[1]); st.setDouble(47, sk.getLeftShoulder()[2]); st.setDouble(48, sk.getRightShoulder()[0]); st.setDouble(49, sk.getRightShoulder()[1]); st.setDouble(50, sk.getRightShoulder()[2]); st.setDouble(51, sk.getLeftWrist()[0]); st.setDouble(52, sk.getLeftWrist()[1]); st.setDouble(53, sk.getLeftWrist()[2]); st.setDouble(54, sk.getRightWrist()[0]); st.setDouble(55, sk.getRightWrist()[1]); st.setDouble(56, sk.getRightWrist()[2]); st.setDouble(57, sk.getShoulderCenter()[0]); st.setDouble(58, sk.getShoulderCenter()[1]); st.setDouble(59, sk.getShoulderCenter()[2]); st.setDouble(60, sk.getSpine()[0]); st.setDouble(61, sk.getSpine()[1]); st.setDouble(62, sk.getSpine()[2]); st.executeUpdate(); // get the auto generated session id to return to the client ResultSet rs = st.getGeneratedKeys(); rs.next(); skeletonId = rs.getInt(1); rs.close(); return skeletonId; }
From source file:uk.ac.cam.cl.dtg.segue.dao.users.PgUsers.java
@Override public boolean linkAuthProviderToAccount(final RegisteredUser user, final AuthenticationProvider provider, final String providerUserId) throws SegueDatabaseException { try (Connection conn = database.getDatabaseConnection()) { PreparedStatement pst;/*from www.j a v a2s . com*/ pst = conn.prepareStatement( "INSERT INTO linked_accounts(user_id, provider, provider_user_id)" + " VALUES (?, ?, ?);", Statement.RETURN_GENERATED_KEYS); pst.setLong(1, user.getId()); pst.setString(2, provider.name()); pst.setString(3, providerUserId); int affectedRows = pst.executeUpdate(); if (affectedRows == 0) { throw new SQLException("Creating linked account record failed, no rows changed"); } return true; } catch (SQLException e) { throw new SegueDatabaseException("Postgres exception", e); } }
From source file:com.hs.mail.imap.dao.MySqlUserDao.java
public long addAlias(final Alias alias) { final String sql = "INSERT INTO alias (alias, deliver_to) VALUES(?, ?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.setString(1, alias.getAlias()); pstmt.setLong(2, alias.getDeliverTo()); return pstmt; }//from w w w . j av a2s . com }, keyHolder); long id = keyHolder.getKey().longValue(); alias.setID(id); return id; }
From source file:backtype.storm.scheduler.adaptive.DataManager.java
public int checkTopology(String stormId) throws Exception { Connection connection = null; Statement statement = null;//www . jav a 2s . c o m ResultSet resultSet = null; int id = -1; logger.debug("Going to check topology " + stormId); try { connection = getConnection(); connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); connection.setAutoCommit(false); statement = connection.createStatement(); String sql = "select id from topology where storm_id = '" + stormId + "'"; logger.debug("SQL query: " + sql); resultSet = statement.executeQuery(sql); if (resultSet.next()) { id = resultSet.getInt(1); logger.debug("Topology found, id: " + id); } else { logger.debug("Topology not found, let's create it"); resultSet.close(); sql = "insert into topology(storm_id) values('" + stormId + "')"; logger.debug("SQL script: " + sql); statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); logger.debug("Retrieving generated id..."); resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { id = resultSet.getInt(1); logger.debug("Ok, id: " + id); } else { throw new Exception("Cannot retrieve generated key"); } } connection.commit(); } catch (Exception e) { connection.rollback(); logger.error("An error occurred checking a topology", e); throw e; } finally { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } return id; }