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:dk.netarkivet.harvester.datamodel.DomainDBDAO.java
/** * Insert the basic configuration info into the DB. This does not establish * the connections with seedlists and passwords, use * {create,update}Config{Passwords,Seedlists}Entries for that. * @param connection /*from w w w.ja va 2s .com*/ * A connection to the database * * @param d * a domain * @param dc * a domainconfiguration * @throws SQLException * If some database error occurs during the insertion process. */ private void insertConfiguration(Connection connection, Domain d, DomainConfiguration dc) throws SQLException { long templateId = DBUtils.selectLongValue(connection, "SELECT template_id FROM ordertemplates WHERE name = ?", dc.getOrderXmlName()); PreparedStatement s = connection.prepareStatement( "INSERT INTO configurations " + "( name, comments, domain_id, template_id, maxobjects, " + "maxrate, maxbytes ) " + "VALUES ( ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); // Id is autogenerated DBUtils.setName(s, 1, dc, Constants.MAX_NAME_SIZE); DBUtils.setComments(s, 2, dc, Constants.MAX_COMMENT_SIZE); s.setLong(3, d.getID()); s.setLong(4, templateId); s.setLong(5, dc.getMaxObjects()); s.setInt(6, dc.getMaxRequestRate()); s.setLong(7, dc.getMaxBytes()); int rows = s.executeUpdate(); if (rows != 1) { String message = "Error inserting configuration " + dc; log.warn(message); throw new IOFailure(message); } dc.setID(DBUtils.getGeneratedID(s)); }
From source file:org.etudes.component.app.jforum.JforumDataServiceImpl.java
/** * creates category/* ww w . j a va2 s. com*/ * @param connection * @param toContextId * @param catName * @param moderated * @return categoy Id */ private int createCategory(Connection connection, String toContextId, String catName, int moderated, int gradable, Date startDate, Date endDate, int lockEndDate, int exisCatgeoryId) throws Exception { if (logger.isDebugEnabled()) logger.debug("creating category with title :" + catName + " for site : " + toContextId); int categoryId = -1; try { int order = 1; String categoryGetMaxOrderSql = "SELECT MAX(display_order) FROM jforum_categories"; PreparedStatement p = connection.prepareStatement(categoryGetMaxOrderSql); ResultSet rs = p.executeQuery(); if (rs.next()) { order = rs.getInt(1) + 1; } rs.close(); p.close(); String categoryAddNewSql = null; if (sqlService.getVendor().equals("oracle")) { categoryAddNewSql = "INSERT INTO jforum_categories (categories_id, title, display_order, moderated, gradable, start_date, end_date, lock_end_date) " + "VALUES (jforum_categories_seq.nextval, ?, ?, ?, ?, ?, ?, ?)"; p = connection.prepareStatement(categoryAddNewSql); p.setString(1, catName); p.setInt(2, order); p.setInt(3, moderated); p.setInt(4, gradable); if (startDate == null) { p.setTimestamp(5, null); } else { p.setTimestamp(5, new Timestamp(startDate.getTime())); } if (endDate == null) { p.setTimestamp(6, null); p.setInt(7, 0); } else { p.setTimestamp(6, new Timestamp(endDate.getTime())); p.setInt(7, lockEndDate); } p.executeUpdate(); p.close(); String categoryLastGeneratedCategoryId = "SELECT jforum_categories_seq.currval FROM DUAL"; p = connection.prepareStatement(categoryLastGeneratedCategoryId); rs = p.executeQuery(); if (rs.next()) { categoryId = rs.getInt(1); } rs.close(); p.close(); } else if (sqlService.getVendor().equalsIgnoreCase("mysql")) { categoryAddNewSql = "INSERT INTO jforum_categories (title, display_order, moderated, gradable, start_date, end_date, lock_end_date) VALUES (?, ?, ?, ?, ?, ?, ?)"; p = connection.prepareStatement(categoryAddNewSql, Statement.RETURN_GENERATED_KEYS); p.setString(1, catName); p.setInt(2, order); p.setInt(3, moderated); p.setInt(4, gradable); if (startDate == null) { p.setTimestamp(5, null); } else { p.setTimestamp(5, new Timestamp(startDate.getTime())); } if (endDate == null) { p.setTimestamp(6, null); p.setInt(7, 0); } else { p.setTimestamp(6, new Timestamp(endDate.getTime())); p.setInt(7, lockEndDate); } p.executeUpdate(); rs = p.getGeneratedKeys(); if (rs.next()) { categoryId = rs.getInt(1); } rs.close(); p.close(); } String courseCategoryAddNewSql = "INSERT INTO jforum_sakai_course_categories (course_id,categories_id) VALUES (?, ?)"; p = connection.prepareStatement(courseCategoryAddNewSql); p.setString(1, toContextId); p.setInt(2, categoryId); p.execute(); p.close(); // create grade if category is gradable if (gradable == 1) { String gradeModelSelectByCategoryId = "SELECT grade_id, context, grade_type, forum_id, topic_id, points, add_to_gradebook, categories_id, min_posts, min_posts_required " + "FROM jforum_grade WHERE forum_id = 0 and topic_id = 0 and categories_id = ?"; PreparedStatement gradePrepStmnt = connection.prepareStatement(gradeModelSelectByCategoryId); gradePrepStmnt.setInt(1, exisCatgeoryId); ResultSet rsGrade = gradePrepStmnt.executeQuery(); float gradePoints = 0f; if (rsGrade.next()) { gradePoints = rsGrade.getFloat("points"); } int addToGradebook = rsGrade.getInt("add_to_gradebook"); boolean minPostsRequired = false; int minPosts = 0; if (rsGrade.getInt("min_posts_required") == 1) { minPostsRequired = true; minPosts = rsGrade.getInt("min_posts"); } rsGrade.close(); gradePrepStmnt.close(); int gradeId = createGrade(connection, toContextId, GRADE_BY_CATEGORY, 0, 0, categoryId, gradePoints, addToGradebook, minPostsRequired, minPosts, catName); // add to gradebook if ((gradeId > 0) && (addToGradebook == 1)) { createGradebookEntry(gradeId, catName, JForumUtil.toDoubleScore(gradePoints), endDate); } } } catch (SQLException e) { if (logger.isErrorEnabled()) logger.error("createCategory():Error occurred while creating category with title : " + catName); e.printStackTrace(); throw e; } return categoryId; }
From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java
/** * {@inheritDoc}/*from ww w . j a v a2 s . c o m*/ */ @Override public void createSubmission(MSubmission submission, Connection conn) { PreparedStatement stmt = null; int result; try { stmt = conn.prepareStatement(crudQueries.getStmtInsertSubmission(), Statement.RETURN_GENERATED_KEYS); stmt.setLong(1, submission.getJobId()); stmt.setString(2, submission.getStatus().name()); stmt.setString(3, submission.getCreationUser()); stmt.setTimestamp(4, new Timestamp(submission.getCreationDate().getTime())); stmt.setString(5, submission.getLastUpdateUser()); stmt.setTimestamp(6, new Timestamp(submission.getLastUpdateDate().getTime())); stmt.setString(7, submission.getExternalJobId()); stmt.setString(8, submission.getExternalLink()); stmt.setString(9, submission.getError().getErrorSummary()); stmt.setString(10, submission.getError().getErrorDetails()); result = stmt.executeUpdate(); if (result != 1) { throw new SqoopException(CommonRepositoryError.COMMON_0009, Integer.toString(result)); } ResultSet rsetSubmissionId = stmt.getGeneratedKeys(); if (!rsetSubmissionId.next()) { throw new SqoopException(CommonRepositoryError.COMMON_0010); } long submissionId = rsetSubmissionId.getLong(1); if (submission.getCounters() != null) { createSubmissionCounters(submissionId, submission.getCounters(), conn); } // Save created persistence id submission.setPersistenceId(submissionId); } catch (SQLException ex) { logException(ex, submission); throw new SqoopException(CommonRepositoryError.COMMON_0031, ex); } finally { closeStatements(stmt); } }
From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java
/** * This method will insert a database entry and <b>SHOULD</b> run asynchronously * * @param offlinePlayer player to be muted * @param moderator the administrator that muted the player, can be null (Console) * @param reason the reason to be muted * @param muteDuration duration to be muted * @return a response to send to the administrator *//*www .j a va 2s . c om*/ public MuteResponse mutePlayer(@NotNull OfflinePlayer offlinePlayer, @Nullable OnlinePlayer moderator, @NotNull final String reason, @NotNull final long muteDuration) { // Check if player is registered if (!offlinePlayer.isRegistered()) return MuteResponse.PLAYER_NOT_REGISTERED; // Set variables int playerId = offlinePlayer.getPlayerId(); long recordDate = System.currentTimeMillis(); long unmuteDate = recordDate + muteDuration; // Check if reason has right size if (!Util.checkStringLength(reason, 4, 128)) return MuteResponse.INVALID_REASON_LENGTH; try { // Retrieve connection Connection connection = LobsterCraft.dataSource.getConnection(); // Prepare statement PreparedStatement preparedStatement = connection.prepareStatement( "INSERT INTO `minecraft`.`mod_muted_players`(`user_mutedId`, `user_moderatorId`, `muteDate`, `unmuteDate`, `reason`) VALUES (?, ?, ?, ?, ?);", Statement.RETURN_GENERATED_KEYS); // Set variables for query preparedStatement.setInt(1, playerId); if (moderator != null) preparedStatement.setInt(2, moderator.getOfflinePlayer().getPlayerId()); // will write null if is null else preparedStatement.setNull(2, Types.INTEGER); preparedStatement.setLong(3, recordDate); preparedStatement.setLong(4, unmuteDate); preparedStatement.setString(5, reason); // Execute statement preparedStatement.execute(); // Retrieve generated keys ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); // Throw error if there is no generated key if (!generatedKeys.next()) throw new SQLException("There is no generated key"); // Create entry MutePlayerEntry mutedPlayerEntry = new MutePlayerEntry(generatedKeys.getLong("mute_index"), moderator != null ? moderator.getOfflinePlayer().getPlayerId() : null, recordDate, unmuteDate, reason); // Add entry to storage synchronized (playerMuteEntries) { playerMuteEntries.putIfAbsent(playerId, new HashSet<>()); playerMuteEntries.get(playerId).add(mutedPlayerEntry); } // Close everything generatedKeys.close(); preparedStatement.close(); connection.close(); // Check if player is online and warn him OnlinePlayer onlinePlayer = offlinePlayer.getOnlinePlayer(null); if (onlinePlayer != null) { StringBuilder stringBuilder = new StringBuilder("cVoc foi silenciado"); if (moderator != null) stringBuilder.append(" por ").append(moderator.getPlayer().getDisplayName()); stringBuilder.append("c at ").append(Util.formatDate(unmuteDate)).append('\n') .append("pela razo: 4\"").append(reason).append('\"'); onlinePlayer.getPlayer().sendMessage(stringBuilder.toString()); } return MuteResponse.SUCCESSFULLY_EXECUTED; } catch (SQLException exception) { exception.printStackTrace(); return MuteResponse.ERROR_OCCURRED; } }
From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java
private void addKeywords(long id, List<String> keywords, boolean isFeed) throws SQLException { if (keywords == null || keywords.size() == 0) { Log.d(TAG, "No keywords to be added for " + (isFeed ? "feed" : "field") + " id: " + id); return;/*from w ww.j a v a 2s. c o m*/ } String sqlSelectKeyword = "SELECT " + IotHubDataHandler.KEY_KEYWORD_ID + " FROM " + IotHubDataHandler.TABLE_KEYWORD + " WHERE " + IotHubDataHandler.KEY_KEYWORD_VALUE + " = ?"; String sqlInsertKeyword = "insert into " + IotHubDataHandler.TABLE_KEYWORD + "(" + IotHubDataHandler.KEY_KEYWORD_VALUE + ") values (?)"; String sqlInsertRelation = isFeed ? ("insert into " + IotHubDataHandler.TABLE_KEYWORD_FEED_REL + "(" + IotHubDataHandler.KEY_KEYWORD_FEED_KEYWORD_ID + "," + IotHubDataHandler.KEY_KEYWORD_FEED_FEED_ID + ") values (?,?)") : ("insert into " + IotHubDataHandler.TABLE_KEYWORD_FIELD_REL + "(" + IotHubDataHandler.KEY_KEYWORD_FIELD_KEYWORD_ID + "," + IotHubDataHandler.KEY_KEYWORD_FIELD_FIELD_ID + ") values (?,?)"); PreparedStatement psSelectKeyword = connection.prepareStatement(sqlSelectKeyword); PreparedStatement psInsertKeyword = connection.prepareStatement(sqlInsertKeyword, Statement.RETURN_GENERATED_KEYS); PreparedStatement psInsertRel = connection.prepareStatement(sqlInsertRelation); for (String keyword : keywords) { psSelectKeyword.setString(1, keyword); ResultSet rs = psSelectKeyword.executeQuery(); if (rs.next()) { long keywordId = rs.getLong(IotHubDataHandler.KEY_KEYWORD_ID); psInsertRel.setLong(1, keywordId); psInsertRel.setLong(2, id); if (psInsertRel.executeUpdate() <= 0) { Log.e(TAG, "Linking keyword " + keyword + " and " + (isFeed ? "feed " : "field ") + id + " did not work"); } } else { psInsertKeyword.setString(1, keyword); psInsertKeyword.executeUpdate(); ResultSet genKeysFeed = psInsertKeyword.getGeneratedKeys(); if (genKeysFeed.next()) { long insertIdKeyword = genKeysFeed.getLong(1); psInsertRel.setLong(1, insertIdKeyword); psInsertRel.setLong(2, id); if (psInsertRel.executeUpdate() <= 0) { Log.e(TAG, "Linking keyword " + keyword + " and " + (isFeed ? "feed " : "field ") + id + " did not work"); } } genKeysFeed.close(); } rs.close(); } psSelectKeyword.close(); psInsertKeyword.close(); psInsertRel.close(); }
From source file:edu.pitt.apollo.db.ApolloDbUtils.java
public int addTextDataContent(String content) throws ApolloDatabaseException, Md5UtilsException { String md5 = ""; try {//from ww w . j av a 2 s .co m md5 = DigestUtils.md5Hex(content); } catch (NullPointerException npe) { System.out.println("?"); } String query = "INSERT IGNORE INTO run_data_content (text_content, md5_hash_of_content, md5_collision_id) values (?,?,?)"; try (Connection conn = datasource.getConnection()) { PreparedStatement pstmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); int highestMD5CollisionId = getHighestMD5CollisionIdForRunDataContent(conn, content); pstmt.setString(1, content); pstmt.setString(2, md5); pstmt.setInt(3, highestMD5CollisionId); int rowsAffected = pstmt.executeUpdate(); if (rowsAffected > 0) { ResultSet rs = pstmt.getGeneratedKeys(); rs.next(); return rs.getInt(1); } else { //should check to see if we have a real collision query = "SELECT id, text_content FROM run_data_content where md5_hash_of_content = ?"; pstmt = conn.prepareStatement(query); pstmt.setString(1, md5); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { // no need to store the data twice // let's not be too hasty, we need to see if it's a TRUE cache hit, // so compare the "content" parameter, with rs.getString(2) // if it's a FALSE cache hit..we need to insert the new content, // with an incremented md5_collision_id String existingContent = rs.getString(2); if (existingContent.equals(content)) { // this is a true cache hit, so return the ID return rs.getInt(1); } else { throw new ApolloDatabaseException("MD5 collision detected (" + md5 + ")!\n\n " + existingContent + " not equal to\n\n " + content); } } else { throw new ApolloDatabaseException("Unable to retrieve data for hash: " + md5 + "!\n\n"); } } } catch (SQLException ex) { throw new ApolloDatabaseException( "SQLException adding text data content with hash \"" + md5 + "\": " + ex.getMessage()); } }
From source file:edu.ku.brc.specify.conversion.ConvertMiscData.java
/** * @param oldDBConn/* w ww . j av a 2 s.c o m*/ * @param newDBConn */ public static void moveGTPNameToCEText1(final Connection oldDBConn, final Connection newDBConn) { String sql = null; try { IdMapperIFace ceMapper = IdMapperMgr.getInstance().addTableMapper("collectingevent", "CollectingEventID", false); Timestamp now = new Timestamp(System.currentTimeMillis()); PreparedStatement pStmt = newDBConn.prepareStatement( "UPDATE collectingeventattribute SET Text3=? WHERE CollectingEventAttributeID=?"); PreparedStatement pStmt2 = newDBConn.prepareStatement( "INSERT INTO collectingeventattribute SET Text3=?, Version=0, DisciplineID=?, TimestampCreated=?, TimestampModified=?", Statement.RETURN_GENERATED_KEYS); PreparedStatement pStmt3 = newDBConn.prepareStatement( "UPDATE collectingevent SET CollectingEventAttributeID=? WHERE CollectingEventID=?"); int cnt = 0; // Query to Create PickList sql = "SELECT c.CollectingEventID, g.Name FROM collectingevent AS c " + "Inner Join stratigraphy AS s ON c.CollectingEventID = s.StratigraphyID " + "Inner Join geologictimeperiod AS g ON s.GeologicTimePeriodID = g.GeologicTimePeriodID "; for (Object[] row : BasicSQLUtils.query(oldDBConn, sql)) { Integer id = (Integer) row[0]; Integer newCEId = ceMapper.get(id); if (newCEId != null) { Vector<Object[]> colList = BasicSQLUtils.query( "SELECT DisciplineID, CollectingEventAttributeID FROM collectingevent WHERE CollectingEventID = " + newCEId); Object[] cols = colList.get(0); if (cols[1] != null) { pStmt.setString(1, (String) row[1]); pStmt.setInt(2, newCEId); int rv = pStmt.executeUpdate(); if (rv != 1) { log.error(String.format("Error updating CEA New Id %d Old: %d rv: %d", newCEId, id, rv)); } } else { Integer disciplineID = (Integer) cols[0]; pStmt2.setString(1, (String) row[1]); pStmt2.setInt(2, disciplineID); pStmt2.setTimestamp(3, now); pStmt2.setTimestamp(4, now); int rv = pStmt2.executeUpdate(); if (rv == 1) { Integer newCEAId = BasicSQLUtils.getInsertedId(pStmt2); if (newCEAId != null) { pStmt3.setInt(1, newCEAId); pStmt3.setInt(2, newCEId); rv = pStmt3.executeUpdate(); if (rv != 1) { log.error(String.format("Error updating CEA New Id %d To CE ID: %d", newCEAId, newCEId)); } } else { log.error("Couldn't get inserted CEAId"); } } else { log.error(String.format("Error updating CEA New Id %d Old: %d rv: %d", newCEId, id, rv)); } } } else { log.error(String.format("No Map for Old CE Id %d", id)); } cnt++; if (cnt % 500 == 0) { log.debug("Count " + cnt); } } log.debug("Count " + cnt); pStmt.close(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.apache.sqoop.repository.derby.DerbyRepositoryHandler.java
/** * Pre-register Driver since the 1.99.3 release NOTE: This should be used only * in the upgrade path//from w w w . ja va2 s . co m */ @Deprecated protected long registerDriver(Connection conn) { if (LOG.isTraceEnabled()) { LOG.trace("Begin Driver loading."); } PreparedStatement baseDriverStmt = null; try { baseDriverStmt = conn.prepareStatement(STMT_INSERT_INTO_CONFIGURABLE, Statement.RETURN_GENERATED_KEYS); baseDriverStmt.setString(1, MDriver.DRIVER_NAME); baseDriverStmt.setString(2, Driver.getClassName()); baseDriverStmt.setString(3, "1"); baseDriverStmt.setString(4, MConfigurableType.DRIVER.name()); int baseDriverCount = baseDriverStmt.executeUpdate(); if (baseDriverCount != 1) { throw new SqoopException(DerbyRepoError.DERBYREPO_0012, Integer.toString(baseDriverCount)); } ResultSet rsetDriverId = baseDriverStmt.getGeneratedKeys(); if (!rsetDriverId.next()) { throw new SqoopException(DerbyRepoError.DERBYREPO_0013); } return rsetDriverId.getLong(1); } catch (SQLException ex) { throw new SqoopException(DerbyRepoError.DERBYREPO_0050, ex); } finally { closeStatements(baseDriverStmt); } }
From source file:org.pentaho.di.core.database.Database.java
/** * Prepare a statement to be executed on the database. * * @param sql// w w w .j av a 2 s.c o m * The SQL to be prepared * @param returnKeys * set to true if you want to return generated keys from an insert statement * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException { try { if (returnKeys) { return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(databaseMeta.stripCR(sql)); } } catch (SQLException ex) { throw new KettleDatabaseException("Couldn't prepare statement:" + Const.CR + sql, ex); } }
From source file:org.dcache.chimera.FsSqlDriver.java
/** * * creates a new id for a tag and stores it into t_tags_inodes table. * * @param uid//from ww w .j a v a 2s . c om * @param gid * @param mode * @return */ long createTagInode(int uid, int gid, int mode) { final String CREATE_TAG_INODE_WITHOUT_VALUE = "INSERT INTO t_tags_inodes (imode, inlink, iuid, igid, isize, " + "ictime, iatime, imtime, ivalue) VALUES (?,1,?,?,0,?,?,?,NULL)"; Timestamp now = new Timestamp(System.currentTimeMillis()); KeyHolder keyHolder = new GeneratedKeyHolder(); int rc = _jdbc.update(con -> { PreparedStatement ps = con.prepareStatement(CREATE_TAG_INODE_WITHOUT_VALUE, Statement.RETURN_GENERATED_KEYS); ps.setInt(1, mode | UnixPermission.S_IFREG); ps.setInt(2, uid); ps.setInt(3, gid); ps.setTimestamp(4, now); ps.setTimestamp(5, now); ps.setTimestamp(6, now); return ps; }, keyHolder); if (rc != 1) { throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(CREATE_TAG_INODE_WITHOUT_VALUE, 1, rc); } return (Long) keyHolder.getKeys().get("itagid"); }