List of usage examples for java.sql ResultSet getByte
byte getByte(String columnLabel) throws SQLException;
ResultSet
object as a byte
in the Java programming language. From source file:com.flexive.ejb.beans.AccountEngineBean.java
/** * {@inheritDoc}/* w w w .j av a 2 s . com*/ */ @Override @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Role> getRoles(long accountId, RoleLoadMode mode) throws FxApplicationException { Connection con = null; Statement stmt = null; String curSql; final UserTicket ticket = getRequestTicket(); try { // Obtain a database connection con = Database.getDbConnection(); // Check the user long mandator = getMandatorForAccount(con, accountId); // Permission checks (2) if (!ticket.isGlobalSupervisor()) { if (mandator != ticket.getMandatorId()) throw new FxNoAccessException("ex.account.roles.wrongMandator", accountId); } // Load the roles curSql = "SELECT DISTINCT ROLE FROM " + TBL_ROLE_MAPPING + " WHERE " + ((mode == RoleLoadMode.ALL || mode == RoleLoadMode.FROM_USER_ONLY) ? "ACCOUNT=" + accountId : "") + ((mode == RoleLoadMode.ALL) ? " OR " : "") + ((mode == RoleLoadMode.ALL || mode == RoleLoadMode.FROM_GROUPS_ONLY) ? " USERGROUP IN (SELECT USERGROUP FROM " + TBL_ASSIGN_GROUPS + " WHERE ACCOUNT=" + accountId + " )" : ""); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(curSql); List<Role> result = new ArrayList<Role>(15); while (rs != null && rs.next()) result.add(Role.getById(rs.getByte(1))); if (LOG.isDebugEnabled()) LOG.debug("Role for user [" + accountId + "]: " + result); return result; } catch (SQLException exc) { throw new FxLoadException(LOG, exc, "ex.account.roles.loadFailed.sql", accountId, exc.getMessage()); } finally { Database.closeObjects(AccountEngineBean.class, con, stmt); } }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
/** * Mock objects allow us to produce warnings at will *//* w ww.jav a 2 s . co m*/ public void testFatalWarning() throws Exception { String sql = "SELECT forename from custmr"; SQLWarning warnings = new SQLWarning("My warning"); MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next(); ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockStatement.executeQuery(sql); ctrlStatement.setReturnValue(mockResultSet); mockStatement.getWarnings(); ctrlStatement.setReturnValue(warnings); mockStatement.close(); ctrlStatement.setVoidCallable(); mockConnection.createStatement(); ctrlConnection.setReturnValue(mockStatement); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); JdbcTemplate t = new JdbcTemplate(mockDataSource); t.setIgnoreWarnings(false); try { t.query(sql, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { rs.getByte(1); } }); fail("Should have thrown exception on warning"); } catch (SQLWarningException ex) { // Pass assertTrue("Root cause of warning was correct", ex.getCause() == warnings); } ctrlResultSet.verify(); ctrlStatement.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testIgnoredWarning() throws Exception { String sql = "SELECT forename from custmr"; SQLWarning warnings = new SQLWarning("My warning"); MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next();//from w w w .j a v a 2 s . co m ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockStatement.executeQuery(sql); ctrlStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); mockConnection.createStatement(); ctrlConnection.setReturnValue(mockStatement); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); // Too long: truncation JdbcTemplate template = new JdbcTemplate(mockDataSource); template.setIgnoreWarnings(true); template.query(sql, new RowCallbackHandler() { public void processRow(ResultSet rs) throws java.sql.SQLException { rs.getByte(1); } }); ctrlResultSet.verify(); ctrlStatement.verify(); }
From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java
/** * This method will cache every registered player. Should run on start, so we don't need to synchronize it. * * @param connection MySQL connection// w w w . j a v a2s . co m * @throws SQLException in case of something going wrong, should stop the server on start */ private void cacheOfflinePlayers(@NotNull final Connection connection) throws SQLException { long start = System.nanoTime(); // Prepare statement and execute query PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM minecraft.user_profiles;"); ResultSet resultSet = preparedStatement.executeQuery(); // Iterate through all results while (resultSet.next()) { String playerName = resultSet.getString("playerName").toLowerCase(); // Check for the nullity of some variables Integer cityId = resultSet.getInt("city_cityId"); if (resultSet.wasNull()) cityId = null; Byte cityOccupationId = resultSet.getByte("cityOccupation"); if (resultSet.wasNull()) cityOccupationId = null; OfflinePlayer offlinePlayer = new OfflinePlayer(resultSet.getInt("playerId"), playerName, resultSet.getString("password"), resultSet.getDouble("moneyAmount"), cityId, CityOccupation.fromId(cityOccupationId), resultSet.getLong("lastTimeOnline"), resultSet.getLong("timePlayed"), resultSet.getString("lastIp")); registeredOfflinePlayers_name.put(playerName, offlinePlayer); registeredOfflinePlayers_id.put(offlinePlayer.getPlayerId(), offlinePlayer); // Check if player has a city if (offlinePlayer.getCityId() != null) { if (!registeredOfflinePlayers_cityId.containsKey(offlinePlayer.getCityId())) registeredOfflinePlayers_cityId.put(offlinePlayer.getCityId(), new HashSet<>()); registeredOfflinePlayers_cityId.get(offlinePlayer.getCityId()).add(offlinePlayer); } } // Close everything resultSet.close(); preparedStatement.close(); // Announce values LobsterCraft.logger.info(Util.appendStrings("Took us ", Util.formatDecimal( (double) (System.nanoTime() - start) / (double) TimeUnit.MILLISECONDS.toNanos(1)), "ms to retrieve ", registeredOfflinePlayers_id.size(), " players.")); }
From source file:com.flexive.ejb.beans.AccountEngineBean.java
/** * {@inheritDoc}//from w w w . j a va 2 s .c om */ @Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public List<ACLAssignment> loadAccountAssignments(long accountId) throws FxApplicationException { Connection con = null; PreparedStatement stmt = null; String curSql; UserTicket ticket = getRequestTicket(); // Security checks if (!ticket.isGlobalSupervisor() && (!(accountId == ticket.getUserId() || accountId == Account.USER_GUEST))) { try { Account usr = load(accountId); if (ticket.isMandatorSupervisor() && ticket.getMandatorId() == usr.getMandatorId()) { // MandatorSupervisor may access all users within his domain } else { FxNoAccessException nae = new FxNoAccessException( "You may not access the ACLAssignment of user [" + accountId + "]"); if (LOG.isInfoEnabled()) LOG.info(nae); throw nae; } } catch (FxNotFoundException exc) { return new ArrayList<ACLAssignment>(0); } } try { // Obtain a database connection con = Database.getDbConnection(); // Fetch assignments // 1 2 3 4 5 6 7 curSql = "SELECT DISTINCT ass.USERGROUP,ass.ACL,ass.PREAD,ass.PEDIT,ass.PREMOVE,ass.PEXPORT,ass.PREL," + // 8 "ass.PCREATE, " + // 9 "(SELECT acl.CAT_TYPE FROM " + TBL_ACLS + " acl WHERE acl.ID=ass.ACL)" + // 10 11 12 13 ",ass.CREATED_BY,ass.CREATED_AT,ass.MODIFIED_BY,ass.MODIFIED_AT " + "FROM " + TBL_ACLS_ASSIGNMENT + " ass " + "WHERE ass.USERGROUP IN (SELECT grp.USERGROUP FROM " + TBL_ASSIGN_GROUPS + " grp WHERE grp.ACCOUNT=?)" + " OR ass.USERGROUP=" + UserGroup.GROUP_OWNER; stmt = con.prepareStatement(curSql); stmt.setLong(1, accountId); ResultSet rs = stmt.executeQuery(); // Read the data List<ACLAssignment> result = new ArrayList<ACLAssignment>(50); while (rs != null && rs.next()) { long groupId = rs.getLong(1); result.add(new ACLAssignment(rs.getLong(2), groupId, rs.getBoolean(3), rs.getBoolean(4), rs.getBoolean(7), rs.getBoolean(5), rs.getBoolean(6), rs.getBoolean(8), ACLCategory.getById(rs.getByte(9)), LifeCycleInfoImpl.load(rs, 10, 11, 12, 13))); } return result; } catch (SQLException exc) { FxLoadException dbe = new FxLoadException( "Failed to load the ACL assignments for user [" + accountId + "]: " + exc.getMessage(), exc); LOG.error(dbe); throw dbe; } finally { Database.closeObjects(ACLEngineBean.class, con, stmt); } }
From source file:com.draagon.meta.manager.db.driver.GenericSQLDriver.java
protected void parseField(Object o, MetaField f, ResultSet rs, int j) throws SQLException { switch (f.getType()) { case MetaField.BOOLEAN: { boolean bv = rs.getBoolean(j); if (rs.wasNull()) { f.setBoolean(o, null);// w w w . j a v a2s .c om } else { f.setBoolean(o, new Boolean(bv)); } } break; case MetaField.BYTE: { byte bv = rs.getByte(j); if (rs.wasNull()) { f.setByte(o, null); } else { f.setByte(o, new Byte(bv)); } } break; case MetaField.SHORT: { short sv = rs.getShort(j); if (rs.wasNull()) { f.setShort(o, null); } else { f.setShort(o, new Short(sv)); } } break; case MetaField.INT: { int iv = rs.getInt(j); if (rs.wasNull()) { f.setInt(o, null); } else { f.setInt(o, new Integer(iv)); } } break; case MetaField.DATE: { Timestamp tv = rs.getTimestamp(j); if (rs.wasNull()) { f.setDate(o, null); } else { f.setDate(o, new java.util.Date(tv.getTime())); } } break; case MetaField.LONG: { long lv = rs.getLong(j); if (rs.wasNull()) { f.setLong(o, null); } else { f.setLong(o, new Long(lv)); } } break; case MetaField.FLOAT: { float fv = rs.getFloat(j); if (rs.wasNull()) { f.setFloat(o, null); } else { f.setFloat(o, new Float(fv)); } } break; case MetaField.DOUBLE: { double dv = rs.getDouble(j); if (rs.wasNull()) { f.setDouble(o, null); } else { f.setDouble(o, new Double(dv)); } } break; case MetaField.STRING: f.setString(o, rs.getString(j)); break; case MetaField.OBJECT: f.setObject(o, rs.getObject(j)); break; } }
From source file:org.dbist.dml.impl.DmlJdbc.java
private static Object toRequiredType(ResultSet rs, int index, Class<?> requiredType) throws SQLException { if (requiredType == null) return rs.getObject(index); if (ValueUtils.isPrimitive(requiredType)) { if (requiredType.equals(String.class)) return rs.getString(index); if (requiredType.equals(Character.class) || requiredType.equals(char.class)) { String str = rs.getString(index); if (str == null || str.length() == 0) return null; return str.charAt(0); }//from w w w. jav a 2s . c o m if (requiredType.equals(BigDecimal.class)) return rs.getBigDecimal(index); if (requiredType.equals(Date.class)) return rs.getTimestamp(index); if (requiredType.equals(Double.class) || requiredType.equals(double.class)) return rs.getDouble(index); if (requiredType.equals(Float.class) || requiredType.equals(float.class)) return rs.getFloat(index); if (requiredType.equals(Long.class) || requiredType.equals(long.class)) return rs.getLong(index); if (requiredType.equals(Integer.class) || requiredType.equals(int.class)) return rs.getInt(index); if (requiredType.equals(Boolean.class) || requiredType.equals(boolean.class)) return rs.getBoolean(index); if (requiredType.equals(Byte[].class) || requiredType.equals(byte[].class)) return rs.getBytes(index); if (requiredType.equals(Byte.class) || requiredType.equals(byte.class)) return rs.getByte(index); } return rs.getObject(index); }
From source file:org.ojbc.intermediaries.sn.dao.TestSubscriptionSearchQueryDAO.java
@Test @DirtiesContext//from w ww. ja va 2s . c o m public void testSubscribe_noExistingSubscriptions() throws Exception { Statement s = dataSource.getConnection().createStatement(); Map<String, String> subjectIds = new HashMap<String, String>(); subjectIds.put(SubscriptionNotificationConstants.SID, "1234"); subjectIds.put(SubscriptionNotificationConstants.SUBSCRIPTION_QUALIFIER, "ABCDE"); ResultSet rs = s.executeQuery("select * from subscription"); int recordCount = 0; while (rs.next()) { recordCount++; } LocalDate currentDate = new LocalDate(); int subscriptionId = subscriptionSearchQueryDAO.subscribe(null, "topic", "2013-01-01", "2013-01-01", subjectIds, new HashSet<String>(Arrays.asList("none@none.com")), "offenderName", "systemName", "ABCDE", "CI", "SYSTEM", currentDate, "0123ABC").intValue(); rs = s.executeQuery("select * from subscription"); int postRecordCount = 0; while (rs.next()) { postRecordCount++; int id = rs.getInt("ID"); if (id == subscriptionId) { assertEquals("topic", rs.getString("TOPIC")); DateTime d = new DateTime(rs.getDate("STARTDATE")); assertEquals(2013, d.getYear()); assertEquals(1, d.getMonthOfYear()); assertEquals(1, d.getDayOfMonth()); d = new DateTime(rs.getDate("ENDDATE")); assertEquals(2013, d.getYear()); assertEquals(1, d.getMonthOfYear()); assertEquals(1, d.getDayOfMonth()); assertEquals("systemName", rs.getString("SUBSCRIBINGSYSTEMIDENTIFIER")); assertEquals("offenderName", rs.getString("SUBJECTNAME")); assertEquals(1, rs.getByte("ACTIVE")); Date lastValidationDateColValue = rs.getDate("lastValidationDate"); assertNotNull(lastValidationDateColValue); DateTime lastValidationDate = new DateTime(lastValidationDateColValue); assertEquals(currentDate.toDateTimeAtStartOfDay().toDate(), lastValidationDate.toDate()); assertEquals("0123ABC", rs.getString("agency_case_number")); } } assertEquals(1, postRecordCount - recordCount); rs.close(); rs = s.executeQuery("select * from notification_mechanism where subscriptionid=" + subscriptionId); postRecordCount = 0; while (rs.next()) { postRecordCount++; assertEquals(NotificationConstants.NOTIFICATION_MECHANISM_EMAIL, rs.getString("NOTIFICATIONMECHANISMTYPE")); assertEquals("none@none.com", rs.getString("NOTIFICATIONADDRESS")); } assertEquals(1, postRecordCount); rs.close(); rs = s.executeQuery("select * from subscription_subject_identifier where subscriptionid=" + subscriptionId); // ResultSetMetaData rsmd = rs.getMetaData(); // for (int i=0;i < rsmd.getColumnCount();i++) { // log.info(rsmd.getColumnLabel(i+1) + ", " + // rsmd.getColumnClassName(i+1)); // } postRecordCount = 0; while (rs.next()) { postRecordCount++; String identifierName = rs.getString("IdentifierName"); if ("SID".equals(identifierName)) { assertEquals("1234", rs.getString("IdentifierValue")); } else if ("subscriptionQualifier".equals(identifierName)) { assertEquals("ABCDE", rs.getString("IdentifierValue")); } else { throw new IllegalStateException("Unexpected identifier: " + identifierName); } } assertEquals(2, postRecordCount); s.close(); }
From source file:org.apache.bigtop.itest.hive.TestJdbc.java
@Test public void preparedStmtAndResultSet() throws SQLException { final String tableName = "bigtop_jdbc_psars_test_table"; try (Statement stmt = conn.createStatement()) { stmt.execute("drop table if exists " + tableName); stmt.execute("create table " + tableName + " (bo boolean, ti tinyint, db double, fl float, " + "i int, lo bigint, sh smallint, st varchar(32))"); }/*from w w w . ja v a2s . com*/ // NOTE Hive 1.2 theoretically support binary, Date & Timestamp in JDBC, but I get errors when I // try to put them in the query. try (PreparedStatement ps = conn .prepareStatement("insert into " + tableName + " values (?, ?, ?, ?, ?, ?, ?, ?)")) { ps.setBoolean(1, true); ps.setByte(2, (byte) 1); ps.setDouble(3, 3.141592654); ps.setFloat(4, 3.14f); ps.setInt(5, 3); ps.setLong(6, 10L); ps.setShort(7, (short) 20); ps.setString(8, "abc"); ps.executeUpdate(); } try (PreparedStatement ps = conn.prepareStatement("insert into " + tableName + " (i, st) " + "values(?, ?)", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) { ps.setNull(1, Types.INTEGER); ps.setObject(2, "mary had a little lamb"); ps.executeUpdate(); ps.setNull(1, Types.INTEGER, null); ps.setString(2, "its fleece was white as snow"); ps.clearParameters(); ps.setNull(1, Types.INTEGER, null); ps.setString(2, "its fleece was white as snow"); ps.execute(); } try (Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from " + tableName); ResultSetMetaData md = rs.getMetaData(); int colCnt = md.getColumnCount(); LOG.debug("Column count is " + colCnt); for (int i = 1; i <= colCnt; i++) { LOG.debug("Looking at column " + i); String strrc = md.getColumnClassName(i); LOG.debug("Column class name is " + strrc); int intrc = md.getColumnDisplaySize(i); LOG.debug("Column display size is " + intrc); strrc = md.getColumnLabel(i); LOG.debug("Column label is " + strrc); strrc = md.getColumnName(i); LOG.debug("Column name is " + strrc); intrc = md.getColumnType(i); LOG.debug("Column type is " + intrc); strrc = md.getColumnTypeName(i); LOG.debug("Column type name is " + strrc); intrc = md.getPrecision(i); LOG.debug("Precision is " + intrc); intrc = md.getScale(i); LOG.debug("Scale is " + intrc); boolean boolrc = md.isAutoIncrement(i); LOG.debug("Is auto increment? " + boolrc); boolrc = md.isCaseSensitive(i); LOG.debug("Is case sensitive? " + boolrc); boolrc = md.isCurrency(i); LOG.debug("Is currency? " + boolrc); intrc = md.getScale(i); LOG.debug("Scale is " + intrc); intrc = md.isNullable(i); LOG.debug("Is nullable? " + intrc); boolrc = md.isReadOnly(i); LOG.debug("Is read only? " + boolrc); } while (rs.next()) { LOG.debug("bo = " + rs.getBoolean(1)); LOG.debug("bo = " + rs.getBoolean("bo")); LOG.debug("ti = " + rs.getByte(2)); LOG.debug("ti = " + rs.getByte("ti")); LOG.debug("db = " + rs.getDouble(3)); LOG.debug("db = " + rs.getDouble("db")); LOG.debug("fl = " + rs.getFloat(4)); LOG.debug("fl = " + rs.getFloat("fl")); LOG.debug("i = " + rs.getInt(5)); LOG.debug("i = " + rs.getInt("i")); LOG.debug("lo = " + rs.getLong(6)); LOG.debug("lo = " + rs.getLong("lo")); LOG.debug("sh = " + rs.getShort(7)); LOG.debug("sh = " + rs.getShort("sh")); LOG.debug("st = " + rs.getString(8)); LOG.debug("st = " + rs.getString("st")); LOG.debug("tm = " + rs.getObject(8)); LOG.debug("tm = " + rs.getObject("st")); LOG.debug("tm was null " + rs.wasNull()); } LOG.debug("bo is column " + rs.findColumn("bo")); int intrc = rs.getConcurrency(); LOG.debug("concurrency " + intrc); intrc = rs.getFetchDirection(); LOG.debug("fetch direction " + intrc); intrc = rs.getType(); LOG.debug("type " + intrc); Statement copy = rs.getStatement(); SQLWarning warning = rs.getWarnings(); while (warning != null) { LOG.debug("Found a warning: " + warning.getMessage()); warning = warning.getNextWarning(); } rs.clearWarnings(); } }
From source file:com.jabyftw.lobstercraft.player.PlayerHandlerService.java
/** * This method will cache every ban record. Should run on start, so we don't need to synchronize it. * * @param connection MySQL connection//from w w w.j a v a2 s .c o m * @throws SQLException in case of something going wrong, should stop the server on start */ private void cachePlayerBanRecords(@NotNull final Connection connection) throws SQLException { long start = System.nanoTime(); // Prepare statement PreparedStatement preparedStatement = connection .prepareStatement("SELECT * FROM `minecraft`.`ban_records`;"); // WHERE `banType` = ? OR `unbanDate` > ?;"); // Set variables - do not filter, let's leave the history available for administrator commands //preparedStatement.setByte(1, BanType.PLAYER_PERMANENTLY_BANNED.getTypeId()); // will filter permanent ban //preparedStatement.setLong(2, System.currentTimeMillis()); // will filter unfinished temporary bans // Execute query ResultSet resultSet = preparedStatement.executeQuery(); // Iterate through results while (resultSet.next()) { // Retrieve variables int playerId = resultSet.getInt("user_playerId"); Integer moderatorId = resultSet.getInt("user_moderatorId"); if (resultSet.wasNull()) moderatorId = null; Long unbanDate = resultSet.getLong("unbanDate"); if (resultSet.wasNull()) unbanDate = null; // Insert base set playerBanEntries.putIfAbsent(playerId, new HashSet<>()); // Insert entry playerBanEntries.get(playerId) .add(new BannedPlayerEntry(resultSet.getLong("recordId"), moderatorId, BanType.getBanType(resultSet.getByte("banType")), resultSet.getLong("recordDate"), resultSet.getString("reason"), unbanDate)); } // Close everything resultSet.close(); preparedStatement.close(); // Announce values LobsterCraft.logger.info(Util.appendStrings("Took us ", Util.formatDecimal( (double) (System.nanoTime() - start) / (double) TimeUnit.MILLISECONDS.toNanos(1)), "ms to retrieve ", playerBanEntries.size(), " ban records.")); }