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:org.kontalk.system.Database.java
/** * Add a new model / row to database./*from w w w. j av a 2 s .c o m*/ * @param table table name the values are inserted into * @param values all objects / row fields that to insert * @return id value of inserted row, -1 if something went wrong */ public synchronized int execInsert(String table, List<Object> values) { // first column is the id String insert = "INSERT INTO " + table + " VALUES (NULL,"; List<String> vList = new ArrayList<>(values.size()); while (vList.size() < values.size()) vList.add("?"); insert += StringUtils.join(vList, ", ") + ")"; try (PreparedStatement stat = mConn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS)) { insertValues(stat, values); stat.executeUpdate(); ResultSet keys = stat.getGeneratedKeys(); return keys.getInt(1); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "can't execute insert: " + insert + " " + values, ex); return -1; } }
From source file:org.wso2.carbon.social.adaptor.DefaultQueryAdaptor.java
private PreparedStatement getInsertCommentActivityPreparedStatement(Connection connection, String json, String targetId, String userId, String tenantDomain, int totalLikes, int totalUnlikes, int timeStamp) throws SQLException { PreparedStatement commentStatement; if (log.isDebugEnabled()) { log.debug(preparedStatementMsg + INSERT_COMMENT_SQL + " json: " + json + " targetId: " + targetId + " userId: " + userId + " tenantDomain: " + tenantDomain); }//from ww w . j a v a 2 s. c o m commentStatement = connection.prepareStatement(INSERT_COMMENT_SQL, Statement.RETURN_GENERATED_KEYS); commentStatement.setString(1, json); commentStatement.setString(2, targetId); commentStatement.setString(3, userId); commentStatement.setString(4, tenantDomain); commentStatement.setInt(5, totalLikes); commentStatement.setInt(6, totalUnlikes); commentStatement.setInt(7, timeStamp); return commentStatement; }
From source file:com.act.lcms.db.model.CuratedStandardMetlinIon.java
private CuratedStandardMetlinIon insertCuratedStandardMetlinIon(DB db, LocalDateTime createdAtDate, String author, String bestMetlinIon, String note, Integer standardIonResultId) throws SQLException, IOException { Connection conn = db.getConn(); try (PreparedStatement stmt = conn.prepareStatement(this.makeInsertQuery(), Statement.RETURN_GENERATED_KEYS)) { bindInsertOrUpdateParameters(stmt, note, createdAtDate, bestMetlinIon, standardIonResultId, author); stmt.executeUpdate();/*from w w w. j ava2 s.com*/ try (ResultSet resultSet = stmt.getGeneratedKeys()) { if (resultSet.next()) { // Get auto-generated id. int id = resultSet.getInt(1); return new CuratedStandardMetlinIon(id, note, createdAtDate, bestMetlinIon, standardIonResultId, author); } else { System.err.format("ERROR: could not retrieve autogenerated key for curated metlin ion\n"); return null; } } } }
From source file:com.softberries.klerk.dao.DocumentDao.java
@Override public void update(Document d) throws SQLException { try {//from w ww .jav a 2 s . c o m init(); st = conn.prepareStatement(SQL_UPDATE_DOCUMENT, Statement.RETURN_GENERATED_KEYS); st.setString(1, d.getTitle()); st.setString(2, d.getNotes()); st.setDate(3, new java.sql.Date(d.getCreatedDate().getTime())); st.setDate(4, new java.sql.Date(d.getTransactionDate().getTime())); st.setDate(5, new java.sql.Date(d.getDueDate().getTime())); st.setString(6, d.getPlaceCreated()); st.setInt(7, d.getDocumentType()); st.setLong(8, d.getCreator().getId()); st.setLong(9, d.getBuyer().getId()); st.setLong(10, d.getSeller().getId()); st.setLong(11, d.getId()); // run the query int i = st.executeUpdate(); System.out.println("i: " + i); if (i == -1) { System.out.println("db error : " + SQL_UPDATE_DOCUMENT); } //delete unused items DocumentItemDao idao = new DocumentItemDao(this.filePath); List<DocumentItem> toDel = new ArrayList<DocumentItem>(); if (d.getId() != null) { List<DocumentItem> existingItems = idao.findAllByDocumentId(d.getId(), run, conn); System.out.println("Existing items: " + existingItems.size()); for (DocumentItem di : existingItems) { System.out.println( "di id: " + di.getId().longValue() + ", di docid: " + di.getDocument_id().longValue()); System.out.println(printAllDIs(d.getItems())); if (!d.getItems().contains(di)) { System.out.println("add to remove: " + di); toDel.add(di); } } } for (DocumentItem di : toDel) { idao.delete(di.getId(), conn); } //update items for (DocumentItem di : d.getItems()) { if (di.getId() != null && di.getId() > 0) { //update System.out.println("update: " + di); idao.update(di, run, conn); } else {//create di.setDocument_id(d.getId()); idao.create(di, run, conn, generatedKeys); System.out.println("insert: " + di); } } conn.commit(); } catch (Exception e) { //rollback the transaction but rethrow the exception to the caller conn.rollback(); e.printStackTrace(); throw new SQLException(e); } finally { close(conn, st, generatedKeys); } }
From source file:at.alladin.rmbt.controlServer.SyncResource.java
@Post("json") public String request(final String entity) { addAllowOrigin();//from w w w. j a v a2 s . c om JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; System.out.println(MessageFormat.format(labels.getString("NEW_SYNC_REQUEST"), getIP())); if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); String lang = request.optString("language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } else lang = settings.getString("RMBT_DEFAULT_LANGUAGE"); // System.out.println(request.toString(4)); if (conn != null) { final JSONArray syncList = new JSONArray(); UUID uuid = null; if (request.optString("uuid").length() > 0) uuid = UUID.fromString(request.getString("uuid")); if (uuid != null && request.optString("sync_code").length() == 0) { String syncCode = ""; try { final PreparedStatement st = conn .prepareStatement("SELECT rmbt_get_sync_code(CAST (? AS UUID)) AS code"); st.setString(1, uuid.toString()); final ResultSet rs = st.executeQuery(); if (rs.next()) syncCode = rs.getString("code"); else errorList.addError("ERROR_DB_GET_SYNC_SQL"); // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"), // new Object[] {uuid})); rs.close(); st.close(); } catch (final SQLException e) { e.printStackTrace(); errorList.addError("ERROR_DB_GET_SYNC_SQL"); // errorList.addError("ERROR_DB_GET_CLIENT_SQL"); } if (errorList.getLength() == 0) { final JSONObject jsonItem = new JSONObject(); //lower case code is easier to enter on mobile devices jsonItem.put("sync_code", syncCode.toLowerCase(Locale.US)); syncList.put(jsonItem); } } else if (uuid != null && request.optString("sync_code").length() > 0) { final String syncCode = request.getString("sync_code").toUpperCase(Locale.US); int syncGroup1 = 0; int uid1 = 0; int syncGroup2 = 0; int uid2 = 0; String msgTitle = labels.getString("SYNC_SUCCESS_TITLE"); String msgText = labels.getString("SYNC_SUCCESS_TEXT"); boolean error = false; try { PreparedStatement st = conn.prepareStatement( "SELECT * FROM client WHERE sync_code = ? AND sync_code_timestamp + INTERVAL '1 month' > NOW()"); st.setString(1, syncCode); ResultSet rs = st.executeQuery(); if (rs.next()) { syncGroup1 = rs.getInt("sync_group_id"); uid1 = rs.getInt("uid"); } else { msgTitle = labels.getString("SYNC_CODE_TITLE"); msgText = labels.getString("SYNC_CODE_TEXT"); error = true; // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"), // new Object[] {uuid})); } rs.close(); st.close(); st = conn.prepareStatement("SELECT * FROM client WHERE uuid = CAST(? AS UUID)"); st.setString(1, uuid.toString()); rs = st.executeQuery(); if (rs.next()) { syncGroup2 = rs.getInt("sync_group_id"); uid2 = rs.getInt("uid"); } else { msgTitle = labels.getString("SYNC_UUID_TITLE"); msgText = labels.getString("SYNC_UUID_TEXT"); error = true; // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"), // new Object[] {uuid})); } rs.close(); st.close(); if (syncGroup1 > 0 && syncGroup1 == syncGroup2) { msgTitle = labels.getString("SYNC_GROUP_TITLE"); msgText = labels.getString("SYNC_GROUP_TEXT"); error = true; } if (uid1 > 0 && uid1 == uid2) { msgTitle = labels.getString("SYNC_CLIENT_TITLE"); msgText = labels.getString("SYNC_CLIENT_TEXT"); error = true; } if (!error) if (syncGroup1 == 0 && syncGroup2 == 0) { int key = 0; // create new group st = conn.prepareStatement("INSERT INTO sync_group(tstamp) " + "VALUES(now())", Statement.RETURN_GENERATED_KEYS); int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_STORE_SYNC_GROUP"); else { rs = st.getGeneratedKeys(); if (rs.next()) // Retrieve the auto generated // key(s). key = rs.getInt(1); rs.close(); } st.close(); if (key > 0) { st = conn.prepareStatement( "UPDATE client SET sync_group_id = ? WHERE uid = ? OR uid = ?"); st.setInt(1, key); st.setInt(2, uid1); st.setInt(3, uid2); affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_UPDATE_SYNC_GROUP"); } } else if (syncGroup1 == 0 && syncGroup2 > 0) { // add 1 to 2 st = conn.prepareStatement("UPDATE client SET sync_group_id = ? WHERE uid = ?"); st.setInt(1, syncGroup2); st.setInt(2, uid1); final int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_UPDATE_SYNC_GROUP"); } else if (syncGroup1 > 0 && syncGroup2 == 0) { // add 2 to 1 st = conn .prepareStatement("UPDATE client SET sync_group_id = ? WHERE uid = ? "); st.setInt(1, syncGroup1); st.setInt(2, uid2); final int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_UPDATE_SYNC_GROUP"); } else if (syncGroup1 > 0 && syncGroup2 > 0) { // add all of 2 to 1 st = conn.prepareStatement( "UPDATE client SET sync_group_id = ? WHERE sync_group_id = ?"); st.setInt(1, syncGroup1); st.setInt(2, syncGroup2); int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_UPDATE_SYNC_GROUP"); else { // Delete empty group st = conn.prepareStatement("DELETE FROM sync_group WHERE uid = ?"); st.setInt(1, syncGroup2); affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_DELETE_SYNC_GROUP"); } } } catch (final SQLException e) { e.printStackTrace(); errorList.addError("ERROR_DB_GET_SYNC_SQL"); // errorList.addError("ERROR_DB_GET_CLIENT_SQL"); } if (errorList.getLength() == 0) { final JSONObject jsonItem = new JSONObject(); jsonItem.put("msg_title", msgTitle); jsonItem.put("msg_text", msgText); jsonItem.put("success", !error); syncList.put(jsonItem); } } answer.put("sync", syncList); } else errorList.addError("ERROR_DB_CONNECTION"); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); return answerString; }
From source file:com.buckwa.dao.impl.excise4.Form23DaoImpl.java
@Override public void create(final Form23 form23) { KeyHolder keyHolder = new GeneratedKeyHolder(); final StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO `form23`").append( " (`form23_id`,`industry_id`,`factory_id`,`create_date`,`create_by`,`update_date`,`update_by`," + "`totalScrap`,`part4flag`,`part4fullName`,`part4Date`," + "`part5flag`,`part5licenseNo`,`part5licenseDate`,`part5billingNo`,`part5billingDate`,`part5amount`,`part5Date`," + "`part6flag`,`part6Date`,`step`)") .append(" VALUES ( NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'0')"); logger.info("SQL : " + sql.toString()); String user = ""; try {//from w w w. j a v a 2s. co m user = BuckWaUtils.getUserNameFromContext(); } catch (BuckWaException e) { e.printStackTrace(); } final String userName = user; jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { Timestamp currentDate = new Timestamp(System.currentTimeMillis()); Industry industry = form23.getIndustry(); Factory factory = form23.getFactory(); PreparedStatement ps = connection.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS); ps.setLong(1, industry.getIndustryId()); if (factory.getFactoryId() != null) { ps.setLong(2, factory.getFactoryId()); } else { ps.setNull(2, java.sql.Types.BIGINT); } ps.setTimestamp(3, currentDate); ps.setString(4, userName); ps.setTimestamp(5, currentDate); ps.setString(6, userName); ps.setBigDecimal(7, form23.getTotalScrap()); ps.setString(8, form23.getPart4flag()); ps.setString(9, form23.getPart4fullName()); ps.setTimestamp(10, currentDate); ps.setString(11, form23.getPart5flag()); ps.setString(12, form23.getPart5licenseNo()); ps.setTimestamp(13, getDateFormString(form23.getPart5licenseDate()));//part5licenseDate ps.setString(14, form23.getPart5billingNo()); ps.setTimestamp(15, getDateFormString(form23.getPart5billingDate()));//part5billingDate ps.setBigDecimal(16, form23.getPart5amount()); ps.setTimestamp(17, currentDate);//part5Date ps.setString(18, form23.getPart6flag());//part5Date ps.setTimestamp(19, currentDate);//part6Date return ps; } }, keyHolder); final Long returnidform23 = keyHolder.getKey().longValue(); form23.setForm23Id(returnidform23); form23.setStep("0"); logger.info("returnidform23 : " + returnidform23); //ID PRODUCT List<Product> products = form23.getProductList(); if (products != null) { final StringBuilder psql = new StringBuilder(); psql.append( "INSERT INTO `form23_product`(`form23_id`,`seq`,`productName`,`size`,`bandColor`,`backgroudColor`,`licenseNo`,`grossnumber200`,`grossnumber400`,`corkScrap`,`totalScrap`,`create_date`,`create_by`, `update_date`,`update_by`,`product_id`) ") .append("VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)"); logger.info("SQL : " + psql.toString()); for (final Product p : products) { jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { Timestamp currentDate = new Timestamp(System.currentTimeMillis()); PreparedStatement ps = connection.prepareStatement(psql.toString(), Statement.RETURN_GENERATED_KEYS); ps.setLong(1, returnidform23); ps.setString(2, p.getSeq()); ps.setString(3, p.getProductName()); ps.setString(4, p.getSize()); ps.setString(5, p.getBandColor()); ps.setString(6, p.getBackgroudColor()); ps.setString(7, p.getLicenseNo()); ps.setBigDecimal(8, p.getGrossnumber200()); ps.setBigDecimal(9, p.getGrossnumber400()); ps.setBigDecimal(10, p.getCorkScrap()); ps.setBigDecimal(11, p.getTotalScrap()); ps.setTimestamp(12, currentDate); ps.setString(13, userName); ps.setTimestamp(14, currentDate); ps.setString(15, userName); return ps; } }, keyHolder); long returnidproduct = keyHolder.getKey().longValue(); p.setProcuctId(returnidproduct); logger.info("returnidproduct : " + returnidproduct); } } }
From source file:org.apache.nifi.admin.dao.impl.StandardActionDAO.java
@Override public Action createAction(Action action) throws DataAccessException { if (action.getUserIdentity() == null) { throw new IllegalArgumentException("User cannot be null."); }// ww w . j av a 2 s. c o m if (action.getTimestamp() == null) { throw new IllegalArgumentException("Action timestamp cannot be null."); } PreparedStatement statement = null; ResultSet rs = null; try { // obtain a statement to insert to the action table statement = connection.prepareStatement(INSERT_ACTION, Statement.RETURN_GENERATED_KEYS); statement.setString(1, StringUtils.left(action.getUserIdentity(), 4096)); statement.setString(2, action.getSourceId()); statement.setString(3, StringUtils.left(action.getSourceName(), 1000)); statement.setString(4, action.getSourceType().toString()); statement.setString(5, action.getOperation().toString()); statement.setTimestamp(6, new java.sql.Timestamp(action.getTimestamp().getTime())); // insert the action int updateCount = statement.executeUpdate(); final FlowChangeAction createdAction = new FlowChangeAction(); createdAction.setUserIdentity(action.getUserIdentity()); createdAction.setSourceId(action.getSourceId()); createdAction.setSourceName(action.getSourceName()); createdAction.setSourceType(action.getSourceType()); createdAction.setOperation(action.getOperation()); createdAction.setTimestamp(action.getTimestamp()); createdAction.setActionDetails(action.getActionDetails()); createdAction.setComponentDetails(action.getComponentDetails()); // get the action id rs = statement.getGeneratedKeys(); if (updateCount == 1 && rs.next()) { createdAction.setId(rs.getInt(1)); } else { throw new DataAccessException("Unable to insert action."); } // close the previous statement statement.close(); // determine the type of component ComponentDetails componentDetails = createdAction.getComponentDetails(); if (componentDetails instanceof FlowChangeExtensionDetails) { createExtensionDetails(createdAction.getId(), (ExtensionDetails) componentDetails); } else if (componentDetails instanceof FlowChangeRemoteProcessGroupDetails) { createRemoteProcessGroupDetails(createdAction.getId(), (RemoteProcessGroupDetails) componentDetails); } // determine the type of action ActionDetails details = createdAction.getActionDetails(); if (details instanceof FlowChangeConnectDetails) { createConnectDetails(createdAction.getId(), (ConnectDetails) details); } else if (details instanceof FlowChangeMoveDetails) { createMoveDetails(createdAction.getId(), (MoveDetails) details); } else if (details instanceof FlowChangeConfigureDetails) { createConfigureDetails(createdAction.getId(), (ConfigureDetails) details); } else if (details instanceof FlowChangePurgeDetails) { createPurgeDetails(createdAction.getId(), (PurgeDetails) details); } return createdAction; } catch (SQLException sqle) { throw new DataAccessException(sqle); } finally { RepositoryUtils.closeQuietly(rs); RepositoryUtils.closeQuietly(statement); } }
From source file:org.ulyssis.ipp.snapshot.Event.java
public void save(Connection connection) throws SQLException { if (id != -1) return;// w w w .j a v a2 s. c om try (PreparedStatement statement = connection.prepareStatement( "INSERT INTO \"events\" (\"time\",\"type\",\"data\",\"removed\") " + "VALUES (?,?,?,?)", Statement.RETURN_GENERATED_KEYS)) { statement.setTimestamp(1, Timestamp.from(time)); String serialized; try { serialized = Serialization.getJsonMapper().writeValueAsString(this); } catch (JsonProcessingException e) { assert false; throw new IllegalStateException(e); // TODO(Roel): is this appropriate? } statement.setString(2, this.getClass().getSimpleName()); statement.setString(3, serialized); statement.setBoolean(4, removed); statement.executeUpdate(); ResultSet keys = statement.getGeneratedKeys(); keys.next(); this.id = keys.getLong(1); } }
From source file:it.fub.jardin.server.DbUtils.java
private ResultSet doUpdate(final Connection connection, final String query) throws SQLException { Statement update = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); update.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); return update.getGeneratedKeys(); }
From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.data.DBConnector.java
/** Executes the given update on the Mysql database. The ResultSet returned contains * the generated keys *//*from w ww. j a v a 2s . c o m*/ public Object[] executeUpdate(String query, Connection conn) throws SQLException { try { log.debug("DBConnector is executing update: " + query); Statement stmt = conn.createStatement(); stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); ResultSet keys = stmt.getGeneratedKeys(); Object[] results = { keys, stmt }; return results; } catch (SQLException e) { log.error("Failed to execute the update: " + query, e); throw e; } }