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:com.tesora.dve.common.DBHelper.java
/** * @param query// www .j av a 2 s . c om * The query to run * @return <b>true</b> if the first result is a ResultSet object; * <b>false</b> if it is an update count or there are no results * @throws SQLException */ public boolean executeQuery(String query) throws SQLException { closeStatement(); checkConnected(); if (logger.isDebugEnabled()) logger.debug("ExecuteQuery '" + query + "' on " + getUrl()); stmt = connection.createStatement(); lastInsertID = 0L; if (isEnableResultSetStreaming()) { stmt.setFetchSize(Integer.MIN_VALUE); } boolean ret = stmt.execute(query, Statement.RETURN_GENERATED_KEYS); if (!ret) { // when stmt.execute returns false it means no result set is // expected get the number of rows affected rowCount = stmt.getUpdateCount(); printLine(rowCount + " rows affected"); ResultSet rs = stmt.getGeneratedKeys(); if (rs.next()) { lastInsertID = rs.getLong(1); } } else { // a stmt returning a result set was run resultSet = stmt.getResultSet(); if (useBufferedQuery) resultSet.setFetchSize(Integer.MAX_VALUE); } return ret; }
From source file:org.kontalk.system.Database.java
/** * Update values (at most one row)/* w ww . j av a 2 s . co m*/ * @param table * @param set * @param id * @return id value of updated row, 0 if something went wrong */ public synchronized int execUpdate(String table, Map<String, Object> set, int id) { String update = "UPDATE OR FAIL " + table + " SET "; List<String> keyList = new ArrayList<>(set.keySet()); List<String> vList = new ArrayList<>(keyList.size()); for (String key : keyList) vList.add(key + " = ?"); update += StringUtils.join(vList, ", ") + " WHERE _id == " + id; // note: looks like driver doesn't support "LIMIT" //update += " LIMIT 1"; try (PreparedStatement stat = mConn.prepareStatement(update, Statement.RETURN_GENERATED_KEYS)) { insertValues(stat, keyList, set); stat.executeUpdate(); ResultSet keys = stat.getGeneratedKeys(); return keys.getInt(1); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "can't execute update: " + update + " " + set, ex); return 0; } }
From source file:edu.corgi.uco.UserBean.java
public AppointmentEvent getAppointment() { String user = FacesContext.getCurrentInstance().getExternalContext().getRemoteUser(); try (Connection conn = dataSource.getConnection()) { PreparedStatement query = conn.prepareStatement("select userid from usertable where email = ?", Statement.RETURN_GENERATED_KEYS); query.setString(1, user);//from w ww . ja v a2 s .c o m ResultSet rs = query.executeQuery(); int uid = 0; if (rs.next()) { uid = rs.getInt(1); } query = conn.prepareStatement( "select * from appointment natural join appointment_slots " + "where userid = ?", Statement.RETURN_GENERATED_KEYS); query.setInt(1, uid); rs = query.executeQuery(); AppointmentEvent ae; Timestamp sd = null; Timestamp ed = null; if (rs.next()) { sd = rs.getTimestamp("startdate"); ed = rs.getTimestamp("enddate"); } ae = new AppointmentEvent("Student Event", sd, ed, 0); return ae; } catch (SQLException ex) { Logger.getLogger(UserBean.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.mfast.evaluations.DCAppSession.java
private void putFrameInDB(SkeletonSequence frame) throws Exception { int measurementFrameId = 0; String sql = "INSERT INTO MeasurementFrame (frameNumber, frameTime, realTimeStampSeconds, realTimeStampMicros, skeletonCount, measurementSessionId) VAlUES(?,?,?,?,?,?)"; // first create a new frame entry st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); st.setInt(1, frame.getFrameNumber()); st.setFloat(2, frame.getTimeStamp()); st.setInt(3, frame.getRealTimeStampSeconds()); st.setInt(4, frame.getRealTimeStampMicros()); st.setInt(5, frame.getSkeletonCount()); st.setInt(6, sessionId);//from w w w . j a va 2s. c o m // set the timestamp (this is currnet time when putting it into database!) /* java.util.Date date = new java.util.Date(); Timestamp ts = new Timestamp(date.getTime()); st.setTimestamp(7, ts);*/ st.executeUpdate(); // get the auto generated session id to return to the client ResultSet rs = st.getGeneratedKeys(); rs.next(); measurementFrameId = rs.getInt(1); rs.close(); if (frame.getSkeletons() == null) { return; } for (Skeleton sk : frame.getSkeletons()) { this.putSkeletonInDB(measurementFrameId, sk); } }
From source file:org.forgerock.openidm.repo.jdbc.impl.query.TableQueries.java
/** * Get a prepared statement for the given connection and SQL. May come from * a cache (either local or the host container) * * @param connection/* ww w . j av a 2 s . c o m*/ * db connection to get a prepared statement for * @param sql * the prepared statement SQL * @param autoGeneratedKeys * whether to return auto-generated keys by the DB * @return the prepared statement * @throws SQLException * if parsing or retrieving the prepared statement failed */ public PreparedStatement getPreparedStatement(Connection connection, String sql, boolean autoGeneratedKeys) throws SQLException { // This is where local prepared statement caching could be added for // stand-alone operation. // In the context of a (JavaEE) container rely on its built-in prepared // statement caching // rather than doing it explicitly here. if (autoGeneratedKeys) { return connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(sql); } }
From source file:com.mirth.connect.server.userutil.DatabaseConnection.java
/** * Executes an INSERT/UPDATE statement on the database and returns a CachedRowSet containing any * generated keys.//from ww w . j a v a 2s .c o m * * @param expression * The statement to be executed. * @return A CachedRowSet containing any generated keys. * @throws SQLException */ public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression) throws SQLException { Statement statement = null; try { statement = connection.createStatement(); logger.debug("executing update:\n" + expression); statement.executeUpdate(expression, Statement.RETURN_GENERATED_KEYS); CachedRowSet crs = new MirthCachedRowSet(); crs.populate(statement.getGeneratedKeys()); return crs; } catch (SQLException e) { throw e; } finally { DbUtils.closeQuietly(statement); } }
From source file:at.becast.youploader.database.SQLite.java
public static int saveTemplate(Template template) throws SQLException, IOException { PreparedStatement prest = null; ObjectMapper mapper = new ObjectMapper(); String sql = "INSERT INTO `templates` (`name`, `data`) " + "VALUES (?,?)"; prest = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); prest.setString(1, template.getName()); prest.setString(2, mapper.writeValueAsString(template)); prest.execute();/*ww w. ja v a 2 s.c om*/ ResultSet rs = prest.getGeneratedKeys(); prest.close(); if (rs.next()) { int id = rs.getInt(1); rs.close(); return id; } else { return -1; } }
From source file:com.ywang.alone.handler.task.AuthTask.java
/** * { 'key':'2597aa1d37d432a','fid':'1020293' } * /*from w w w .ja v a 2 s .c o m*/ * @param param * @return */ private static String follow(String msg) { JSONObject jsonObject = AloneUtil.newRetJsonObject(); JSONObject param = JSON.parseObject(msg); String token = param.getString("key"); String userId = null; if (StringUtils.isEmpty(token)) { jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH); jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH); jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH); return jsonObject.toJSONString(); } Jedis jedis = JedisUtil.getJedis(); Long tokenTtl = jedis.ttl("TOKEN:" + token); if (tokenTtl == -1) { jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH); jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH); jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH); } else { userId = jedis.get("TOKEN:" + token); LoggerUtil.logMsg("uid is " + userId); } JedisUtil.returnJedis(jedis); if (StringUtils.isEmpty(userId)) { jsonObject.put("ret", Constant.RET.NO_ACCESS_AUTH); jsonObject.put("errCode", Constant.ErrorCode.NO_ACCESS_AUTH); jsonObject.put("errDesc", Constant.ErrorDesc.NO_ACCESS_AUTH); return jsonObject.toJSONString(); } DruidPooledConnection conn = null; PreparedStatement stmt = null; try { conn = DataSourceFactory.getInstance().getConn(); conn.setAutoCommit(false); stmt = conn.prepareStatement("insert into follow (USER_ID, FOLLOWED_ID, `TIME`) VALUES (?,?,?)", Statement.RETURN_GENERATED_KEYS); stmt.setString(1, userId); stmt.setString(2, param.getString("fid").trim()); stmt.setLong(3, System.currentTimeMillis()); int result = stmt.executeUpdate(); if (result != 1) { jsonObject.put("ret", Constant.RET.UPDATE_DB_FAIL); jsonObject.put("errCode", Constant.ErrorCode.UPDATE_DB_FAIL); jsonObject.put("errDesc", Constant.ErrorDesc.UPDATE_DB_FAIL); } conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { LoggerUtil.logServerErr(e); jsonObject.put("ret", Constant.RET.SYS_ERR); jsonObject.put("errCode", Constant.ErrorCode.SYS_ERR); jsonObject.put("errDesc", Constant.ErrorDesc.SYS_ERR); } finally { try { if (null != stmt) { stmt.close(); } if (null != conn) { conn.close(); } } catch (SQLException e) { LoggerUtil.logServerErr(e.getMessage()); } } return jsonObject.toJSONString(); }
From source file:com.adanac.module.blog.dao.ArticleDao.java
public Integer saveOrUpdate(String id, String subject, Status status, Type type, Integer updateCreateTime, String username, String html, String content, String icon) { return execute((TransactionalOperation<Integer>) connection -> { String insertSql = "insert into articles (subject,username,icon,create_date," + "html,content,status,type) values (?,?,?,?,?,?,?,?)"; String updateSql = "update articles set subject=?,username=?,icon=?,html=?,content=?,status=?,type=? where id=?"; if (updateCreateTime == 1) { updateSql = "update articles set subject=?,username=?,icon=?,html=?,content=?,status=?,type=?,create_date=? where id=?"; }//w w w. ja v a2s. com try { PreparedStatement statement = null; if (StringUtils.isBlank(id)) { statement = connection.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, subject); statement.setString(2, username); statement.setString(3, icon == null ? ImageUtil.randomArticleImage(subject, type) : icon); statement.setTimestamp(4, new Timestamp(System.currentTimeMillis())); statement.setString(5, html); statement.setString(6, content); statement.setInt(7, status.getIntValue()); statement.setInt(8, type.getIntValue()); } else { statement = connection.prepareStatement(updateSql); statement.setString(1, subject); statement.setString(2, username); statement.setString(3, icon == null ? ImageUtil.randomArticleImage(subject, type) : icon); statement.setString(4, html); statement.setString(5, content); statement.setInt(6, status.getIntValue()); statement.setInt(7, type.getIntValue()); if (updateCreateTime == 1) { statement.setTimestamp(8, new Timestamp(System.currentTimeMillis())); statement.setInt(9, Integer.valueOf(id)); } else { statement.setInt(8, Integer.valueOf(id)); } } int result = statement.executeUpdate(); if (result > 0 && StringUtils.isBlank(id)) { ResultSet keyResultSet = statement.getGeneratedKeys(); if (keyResultSet.next()) { return keyResultSet.getInt(1); } } if (result > 0) { return Integer.valueOf(id); } } catch (SQLException e) { throw new RuntimeException(e); } return null; }); }
From source file:com.facebook.presto.jdbc.PrestoConnection.java
@Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { if (autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS) { throw new SQLFeatureNotSupportedException("Auto generated keys must be NO_GENERATED_KEYS"); }/*www .j a v a2s . c om*/ return prepareStatement(sql); }