List of usage examples for java.sql ResultSet getLong
long getLong(String columnLabel) throws SQLException;
ResultSet
object as a long
in the Java programming language. From source file:de.iritgo.aktario.jdbc.LoadAllObjects.java
/** * Perform the command./*from ww w .j a v a 2 s .c o m*/ */ public void perform() { if (properties.getProperty("type") == null) { Log.logError("persist", "LoadObjects", "The type of the objects to load wasn't specified"); return; } final String type = ((String) properties.getProperty("type")); final AbstractIObjectFactory factory = (AbstractIObjectFactory) Engine.instance().getIObjectFactory(); IObject sample = null; try { sample = factory.newInstance(type); } catch (NoSuchIObjectException ignored) { Log.logError("persist", "LoadObjects", "Attemting to load objects of unknown type '" + type + "'"); return; } if (!DataObject.class.isInstance(sample)) { Log.logError("persist", "LoadObjects", "Attemting to load objects that are not persitable"); return; } final BaseRegistry registry = Engine.instance().getBaseRegistry(); JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager"); DataSource dataSource = jdbcManager.getDefaultDataSource(); try { QueryRunner query = new QueryRunner(dataSource); ResultSetHandler resultSetHandler = properties.get("resultSetHandle") != null ? (ResultSetHandler) properties.get("resultSetHandler") : new ResultSetHandler() { public Object handle(ResultSet rs) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); int numObjects = 0; while (rs.next()) { try { DataObject object = (DataObject) factory.newInstance(type); object.setUniqueId(rs.getLong("id")); for (Iterator i = object.getAttributes().entrySet().iterator(); i.hasNext();) { Map.Entry attribute = (Map.Entry) i.next(); if (attribute.getValue() instanceof IObjectList) { // loadList ( // dataSource, object, // object.getIObjectListAttribute ( // (String) attribute.getKey ())); } else { object.setAttribute((String) attribute.getKey(), rs.getObject((String) attribute.getKey())); } } registry.add(object); ++numObjects; } catch (NoSuchIObjectException ignored) { } } return new Integer(numObjects); } }; Object numObjects = query.query("select * from " + type, resultSetHandler); Log.logVerbose("persist", "LoadObjects", "Successfully loaded " + numObjects + " objects of type '" + type + "'"); } catch (Exception x) { Log.logError("persist", "LoadObjects", "Error while loading objects of type '" + type + "': " + x); } }
From source file:com.mobilewallet.users.dao.UserDAO.java
public User userInfo(long userId) { Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; User user = null;/* w w w . java2 s .com*/ try { connection = dataSource.getConnection(); pstmt = connection.prepareStatement(getUserInfoQuery); pstmt.setLong(1, userId); rs = pstmt.executeQuery(); if (rs.next()) { user = new User(); user.setUserId(rs.getLong("u_id")); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } } catch (Exception ex) { } try { if (pstmt != null) { pstmt.close(); } } catch (Exception ex) { } try { if (connection != null) { connection.close(); } } catch (Exception ex) { } } return user; }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
private void migrateUserCredentials(Connection conn) { System.out.println("Begin migrate user credentials"); PreparedStatement pstmt = null; ResultSet rs = null; try {//from w ww. ja v a 2 s. c om pstmt = conn.prepareStatement("select id, secret_key from user"); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String secretKey = rs.getString(2); if (secretKey == null || secretKey.isEmpty()) { continue; } String encryptedSecretKey = migrateValue(secretKey); pstmt = conn.prepareStatement("update user set secret_key=? where id=?"); pstmt.setBytes(1, encryptedSecretKey.getBytes("UTF-8")); pstmt.setLong(2, id); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable update user secret key ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable update user secret key ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } System.out.println("End migrate user credentials"); }
From source file:com.tesora.dve.common.DBHelper.java
/** * @param query//w w w . j a va2 s.c o m * 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:eionet.transfer.dao.MetadataServiceJdbc.java
@Override public Upload getById(String id) { String query = "SELECT id, expires, filename, uploader, contenttype, filesize FROM uploads WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); Upload uploadRec = jdbcTemplate.queryForObject(query, new Object[] { id }, new RowMapper<Upload>() { @Override//from ww w .j av a 2 s. co m public Upload mapRow(ResultSet rs, int rowNum) throws SQLException { Upload uploadRec = new Upload(); uploadRec.setId(rs.getString("id")); uploadRec.setFilename(rs.getString("filename")); uploadRec.setExpires(rs.getDate("expires")); uploadRec.setUploader(rs.getString("uploader")); uploadRec.setContentType(rs.getString("contenttype")); uploadRec.setSize(rs.getLong("filesize")); return uploadRec; } }); return uploadRec; }
From source file:de.ingrid.importer.udk.strategy.v30.IDCStrategy3_0_0_fixFreeEntry.java
private void updateT01Object() throws Exception { if (log.isInfoEnabled()) { log.info("Updating t01_object..."); }/*www.java 2s . co m*/ if (log.isInfoEnabled()) { log.info("Map old vertical_extent_vdatum to new vertical_extent_vdatum_key/_value ..."); } // select via node to also update index String sql = "select distinct objNode.id as objNodeId, objNode.obj_id as objIdWorking, " + "obj.id as objId, obj.vertical_extent_vdatum, obj.obj_uuid " + "from t01_object obj, object_node objNode " + "where obj.obj_uuid = objNode.obj_uuid"; Statement st = jdbc.createStatement(); ResultSet rs = jdbc.executeQuery(sql, st); Set<Long> processedNodeIds = new HashSet<Long>(); int numProcessed = 0; String catalogLanguage = getCatalogLanguageFromDescriptor(); // Integer igcLangCode = UtilsLanguageCodelist.getCodeFromShortcut(catalogLanguage); while (rs.next()) { long objNodeId = rs.getLong("objNodeId"); long objIdWorking = rs.getLong("objIdWorking"); long objId = rs.getLong("objId"); String objUuid = rs.getString("obj_uuid"); int verticalExtentVdatumKey = rs.getInt("vertical_extent_vdatum"); String verticalExtentVdatumValue = null; // determine languages if (verticalExtentVdatumKey <= 0) { continue; } verticalExtentVdatumValue = readSyslistValue(101, verticalExtentVdatumKey, catalogLanguage); jdbc.executeUpdate("UPDATE t01_object SET " + "vertical_extent_vdatum_key = " + verticalExtentVdatumKey + ", vertical_extent_vdatum_value = '" + verticalExtentVdatumValue + "'" + " WHERE id = " + objId); // Node may contain different object versions, then we receive nodeId multiple times. // Write Index only once (index contains data of working version!) ! if (!processedNodeIds.contains(objNodeId) && objIdWorking == objId) { JDBCHelper.updateObjectIndex(objNodeId, String.valueOf(verticalExtentVdatumKey), jdbc); JDBCHelper.updateObjectIndex(objNodeId, verticalExtentVdatumValue, jdbc); processedNodeIds.add(objNodeId); } numProcessed++; if (log.isDebugEnabled()) { log.debug("Object " + objUuid + " updated " + "vertical_extent_vdatum: '" + verticalExtentVdatumKey + "' --> '" + verticalExtentVdatumKey + "'/'" + verticalExtentVdatumValue + "'"); } } rs.close(); st.close(); if (log.isInfoEnabled()) { log.info("Updated " + numProcessed + " objects... done"); log.info("Updating t01_object... done"); } }
From source file:com.flexive.ejb.beans.HistoryTrackerEngineBean.java
/** * {@inheritDoc}/* w w w .j a va 2s . c o m*/ */ @Override public List<FxHistory> getEntries(String keyMatch, Long accountMatch, Long typeMatch, Long contentMatch, Date startDate, Date endDate, int maxEntries) { List<FxHistory> ret = new ArrayList<FxHistory>(100); Connection con = null; PreparedStatement ps = null; try { con = Database.getDbConnection(); String query = ""; if (accountMatch != null) query += " AND ACCOUNT=" + accountMatch; if (typeMatch != null) query += " AND TYPEID=" + typeMatch; if (contentMatch != null) query += " AND PKID=" + contentMatch; ps = con.prepareStatement(StorageManager.escapeReservedWords(HISTORY_SELECT) + " WHERE TIMESTP>=? AND TIMESTP<=? AND ACTION_KEY LIKE ? " + query + " ORDER BY TIMESTP DESC"); ps.setLong(1, startDate == null ? 0 : startDate.getTime()); ps.setLong(2, endDate == null ? Long.MAX_VALUE - 1 : endDate.getTime()); ps.setString(3, (StringUtils.isEmpty(keyMatch) ? "" : keyMatch) + "%"); ResultSet rs = ps.executeQuery(); boolean loadData = FxContext.getUserTicket().isGlobalSupervisor(); int count = 0; while (rs != null && rs.next()) { if (count++ >= maxEntries) break; long typeId = rs.getLong(8); if (rs.wasNull()) typeId = -1; ret.add(new FxHistory(rs.getLong(3), rs.getLong(1), rs.getString(2), rs.getString(4), rs.getString(5).split("\\|"), typeId, rs.getLong(9), rs.getInt(10), rs.getString(6), rs.getString(7), loadData ? rs.getString(11) : "No permission to load to data!", rs.getString(12))); } } catch (Exception ex) { LOG.error(ex.getMessage()); } finally { Database.closeObjects(HistoryTrackerEngineBean.class, con, ps); } return ret; }
From source file:de.tu_berlin.dima.oligos.db.oracle.OracleColumnConnector.java
/** * Retrieves the raw histogram from the Oracle Database catalog regardless of its type (i.e. frequency, height * balanced, or hybrid histogram). Cumulative frequencies are converted to absolute frequencies. * <br />/* w w w . j a va 2 s . c o m*/ * For example * <pre> * value 1 1 * value 2 2 * value 3 3 * value 4 4 * ... * </pre> * is converted to * <pre> * value 1 1 * value 2 1 * value 3 1 * value 4 1 * ... * </pre>. * <br /> * The entries are ordered by there respective endpoint_number (before conversion). * @return Mapping of values (bucket boundaries) to there apsolute count and repeat count if present. * @throws SQLException */ @SuppressWarnings("unchecked") public Map<T, Pair<Long, Long>> getRawHistogram() throws SQLException { if (rawHistogram == null) { rawHistogram = new LinkedHashMap<>(); Connection conn = connector.getConnection(); PreparedStatement stmt = conn.prepareStatement(HISTOGRAM_QUERY); stmt.setString(1, schema); stmt.setString(2, table); stmt.setString(3, column); ResultSet result = stmt.executeQuery(); long last = 0L; while (result.next()) { BigDecimal endpointValue = result.getBigDecimal("ENDPOINT_VALUE"); String endpointActualValue = result.getString("ENDPOINT_ACTUAL_VALUE"); long cumulativeCount = result.getLong("ENDPOINT_NUMBER"); long endpointRepeatCount = result.getLong("ENDPOINT_REPEAT_COUNT"); long count = cumulativeCount - last; if (getTypeInfo().getType().equals(String.class) && endpointActualValue != null && endpointActualValue.length() > 0) { rawHistogram.put(parser.fromString(endpointActualValue), Pair.of(count, endpointRepeatCount)); } else { rawHistogram.put((T) OracleUtils.convertFromNumber(endpointValue, getTypeInfo()), Pair.of(count, endpointRepeatCount)); } last = cumulativeCount; } stmt.close(); } return rawHistogram; }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
private void migrateVNCPassword(Connection conn) { System.out.println("Begin migrate VNC password"); PreparedStatement pstmt = null; ResultSet rs = null; try {// w w w.j a va2s . c o m pstmt = conn.prepareStatement("select id, vnc_password from vm_instance"); rs = pstmt.executeQuery(); while (rs.next()) { long id = rs.getLong(1); String value = rs.getString(2); if (value == null || value.isEmpty()) { continue; } String encryptedValue = migrateValue(value); pstmt = conn.prepareStatement("update vm_instance set vnc_password=? where id=?"); pstmt.setBytes(1, encryptedValue.getBytes("UTF-8")); pstmt.setLong(2, id); pstmt.executeUpdate(); } } catch (SQLException e) { throw new CloudRuntimeException("Unable update vm_instance vnc_password ", e); } catch (UnsupportedEncodingException e) { throw new CloudRuntimeException("Unable update vm_instance vnc_password ", e); } finally { try { if (rs != null) { rs.close(); } if (pstmt != null) { pstmt.close(); } } catch (SQLException e) { } } System.out.println("End migrate VNC password"); }
From source file:org.traccar.database.QueryBuilder.java
public long executeUpdate() throws SQLException { if (query != null) { try {// w w w .j a v a 2 s .com statement.execute(); if (returnGeneratedKeys) { ResultSet resultSet = statement.getGeneratedKeys(); if (resultSet.next()) { return resultSet.getLong(1); } } } finally { statement.close(); connection.close(); } } return 0; }