Java Code Examples for java.sql.ResultSet#wasNull()

The following examples show how to use java.sql.ResultSet#wasNull() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PersistentEnumUserType.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet rs, String[] names,
        SharedSessionContractImplementor session, Object owner)
    throws HibernateException, SQLException
{
    String name = rs.getString(names[0]);
    if (rs.wasNull()) {
        return null;
    }
    for (PersistentEnum value : returnedClass().getEnumConstants()) {
        if (name.equals(value.getId())) {
            return value;
        }
    }
    throw new IllegalStateException(
            "Unknown " + returnedClass().getSimpleName() + " value [" + name + "]");
}
 
Example 2
Source File: OrdinalEnumValueConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public E readValue(ResultSet resultSet, String name) throws SQLException {
	final int ordinal = resultSet.getInt( name );
	final boolean traceEnabled = log.isTraceEnabled();
	if ( resultSet.wasNull() ) {
		if ( traceEnabled ) {
			log.trace(String.format("Returning null as column [%s]", name));
		}
		return null;
	}

	final E enumValue = toDomainValue( ordinal );
	if ( traceEnabled ) {
		log.trace(String.format("Returning [%s] as column [%s]", enumValue, name));
	}

	return enumValue;
}
 
Example 3
Source File: ExtensionAggregateNumbersQuery.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
private TabInformation extractTabInformation(String tabName, ResultSet set) throws SQLException {
    Optional<Integer> tabPriority = Optional.of(set.getInt("tab_priority"));
    if (set.wasNull()) {
        tabPriority = Optional.empty();
    }
    Optional<ElementOrder[]> elementOrder = Optional.ofNullable(set.getString(ExtensionTabTable.ELEMENT_ORDER)).map(ElementOrder::deserialize);

    Icon tabIcon = extractTabIcon(set);

    return new TabInformation(
            tabName,
            tabIcon,
            elementOrder.orElse(ElementOrder.values()),
            tabPriority.orElse(100)
    );
}
 
Example 4
Source File: ImportFromJdbcPlugin.java    From constellation with Apache License 2.0 5 votes vote down vote up
private static void setValue(final GraphWriteMethods wg, final ResultSet rs, final String label, final Attribute attr, final int id) throws SQLException {
    switch (attr.getAttributeType()) {
        case "boolean":
            wg.setBooleanValue(attr.getId(), id, rs.getBoolean(label));
            break;
        case "date":
            final Date d = rs.getDate(label);
            if (!rs.wasNull()) {
                wg.setLongValue(attr.getId(), id, d.getTime());
            }
            break;
        case "datetime":
            final Timestamp ts = rs.getTimestamp(label);
            if (!rs.wasNull()) {
                wg.setLongValue(attr.getId(), id, ts.getTime());
            }
            break;
        case "integer":
            wg.setIntValue(attr.getId(), id, rs.getInt(label));
            break;
        case "float":
            wg.setFloatValue(attr.getId(), id, rs.getFloat(label));
            break;
        case "time":
            final Time t = rs.getTime(label);
            if (!rs.wasNull()) {
                wg.setLongValue(attr.getId(), id, t.getTime());
            }
            break;
        default:
            final String s = rs.getString(label);
            wg.setStringValue(attr.getId(), id, rs.wasNull() ? null : s);
            break;
    }
}
 
Example 5
Source File: DAOFactory.java    From uavstack with Apache License 2.0 5 votes vote down vote up
public Object getResult(ResultSet rs, int columnIndex) throws SQLException {

            Object s = rs.getString(columnIndex);
            if (rs.wasNull()) {
                return null;
            }
            else {
                return s;
            }
        }
 
Example 6
Source File: IncrementGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void getNext( SessionImplementor session ) {

		log.debug("fetching initial value: " + sql);
		
		try {
			PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
			try {
				ResultSet rs = st.executeQuery();
				try {
					if ( rs.next() ) {
						next = rs.getLong(1) + 1;
						if ( rs.wasNull() ) next = 1;
					}
					else {
						next = 1;
					}
					sql=null;
					log.debug("first free id: " + next);
				}
				finally {
					rs.close();
				}
			}
			finally {
				session.getBatcher().closeStatement(st);
			}
			
		}
		catch (SQLException sqle) {
			throw JDBCExceptionHelper.convert(
					session.getFactory().getSQLExceptionConverter(),
					sqle,
					"could not fetch initial value for increment generator",
					sql
				);
		}
	}
 
Example 7
Source File: ComBindingEntryDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BindingEntry mapRow(ResultSet resultSet, int row) throws SQLException {
	BindingEntry readEntry = new BindingEntryImpl();
	readEntry.setBindingEntryDao(bindingEntryDao);
	
	readEntry.setCustomerID(resultSet.getInt("customer_id"));
	readEntry.setMailinglistID(resultSet.getInt("mailinglist_id"));
	readEntry.setMediaType(resultSet.getInt("mediatype"));
	readEntry.setUserType(resultSet.getString("user_type"));
	readEntry.setUserStatus(resultSet.getInt("user_status"));
	readEntry.setChangeDate(resultSet.getTimestamp("timestamp"));
	readEntry.setExitMailingID(resultSet.getInt("exit_mailing_id"));
	if (resultSet.wasNull()) {
		readEntry.setExitMailingID(0);
	}
	
	if (DbUtilities.resultsetHasColumn(resultSet, "entry_mailing_id")) {
		readEntry.setEntryMailingID(resultSet.getInt("entry_mailing_id"));
		if (resultSet.wasNull()) {
			readEntry.setEntryMailingID(0);
		}
	} else {
		readEntry.setEntryMailingID(0);
	}
	
	readEntry.setUserRemark(resultSet.getString("user_remark"));
	if (DbUtilities.resultsetHasColumn(resultSet, "referrer")) {
		readEntry.setReferrer(resultSet.getString("referrer"));
	}
	readEntry.setCreationDate(resultSet.getTimestamp("creation_date"));

	return readEntry;
}
 
Example 8
Source File: NotificationGroupsDao.java    From StatsAgg with Apache License 2.0 5 votes vote down vote up
public Map<Integer,String> getNotificationGroupNames_ById() {
    
    try {

        if (!isConnectionValid()) {
            return new HashMap<>();
        }

        Map<Integer,String> notificationGroupNames_ById = new HashMap<>();
        
        databaseInterface_.createPreparedStatement(NotificationGroupsSql.Select_AllNotificationGroup_IdsAndNames, 1000);
        databaseInterface_.executePreparedStatement();
        
        if (!databaseInterface_.isResultSetValid()) {
            return new HashMap<>();
        }

        ResultSet resultSet = databaseInterface_.getResults();
        
        while (resultSet.next()) {
            Integer id = resultSet.getInt("ID");
            if (resultSet.wasNull()) id = null;
            
            String name = resultSet.getString("NAME");
            if (resultSet.wasNull()) name = null;

            if ((id != null) && (name != null)) notificationGroupNames_ById.put(id, name);
        }
        
        return notificationGroupNames_ById;
    }
    catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        return new HashMap<>();
    }
    finally {
        databaseInterface_.cleanupAutomatic();
    } 
    
}
 
Example 9
Source File: EncryptedBigIntegerType.java    From jasypt with Apache License 2.0 5 votes vote down vote up
public Object nullSafeGet(final ResultSet rs, final String[] names, final Object owner)
        throws HibernateException, SQLException {
    checkInitialization();
    final BigDecimal decimalMessage = rs.getBigDecimal(names[0]);
    if (rs.wasNull()) {
        return null;
    }
    final BigInteger message = 
        decimalMessage.setScale(0, BigDecimal.ROUND_UNNECESSARY).
            unscaledValue();
    return this.encryptor.decrypt(message);
}
 
Example 10
Source File: EnumUserType.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Object nullSafeGet( ResultSet resultSet, String[] names, SharedSessionContractImplementor impl, Object owner )
    throws HibernateException, SQLException
{
    String name = resultSet.getString( names[0] );
    E result = null;
    if ( !resultSet.wasNull() )
    {
        result = Enum.valueOf( clazz, name );
    }
    return result;
}
 
Example 11
Source File: DoubleAttribute.java    From reladomo with Apache License 2.0 5 votes vote down vote up
public void zPopulateValueFromResultSet(int resultSetPosition, int dataPosition, ResultSet rs, AggregateData data, TimeZone databaseTimezone, DatabaseType dt)
        throws SQLException
{
    MutableDouble obj;
    double d = rs.getDouble(resultSetPosition);
    if (rs.wasNull())
    {
        obj = new MutableDouble();
    }
    else
    {
        obj = new MutableDouble(d);
    }
    data.setValueAt(dataPosition, obj);
}
 
Example 12
Source File: Oracle.java    From requery with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean read(ResultSet results, int column) throws SQLException {
    Boolean value = results.getBoolean(column);
    if (results.wasNull()) {
        return null;
    }
    return value;
}
 
Example 13
Source File: TestSql.java    From evosql with Apache License 2.0 5 votes vote down vote up
/**
 * In 1.8.0.2, this fails in client / server due to column type of the
 * second select for b1 being boolean, while the first select is interpreted
 * as varchar. The rowOutputBase class attempts to cast the Java Boolean
 * into String.
 */
public void testUnionColumnTypes() {

    try {
        Connection conn = newConnection();
        Statement  stmt = conn.createStatement();

        stmt.execute("DROP TABLE test1 IF EXISTS");
        stmt.execute("DROP TABLE test2 IF EXISTS");
        stmt.execute("CREATE TABLE test1 (id int, b1 boolean)");
        stmt.execute("CREATE TABLE test2 (id int)");
        stmt.execute("INSERT INTO test1 VALUES(1,true)");
        stmt.execute("INSERT INTO test2 VALUES(2)");

        ResultSet rs = stmt.executeQuery(
            "select id,null as b1 from test2 union select id, b1 from test1");
        Boolean[] array = new Boolean[2];

        for (int i = 0; rs.next(); i++) {
            boolean boole = rs.getBoolean(2);

            array[i] = Boolean.valueOf(boole);

            if (rs.wasNull()) {
                array[i] = null;
            }
        }

        boolean result = (array[0] == null && array[1] == Boolean.TRUE)
                         || (array[0] == Boolean.TRUE && array[1] == null);

        assertTrue(result);
    } catch (SQLException e) {
        e.printStackTrace();
        System.out.println("TestSql.testUnionColumnType() error: "
                           + e.getMessage());
    }
}
 
Example 14
Source File: EncryptedBigIntegerType.java    From jasypt with Apache License 2.0 5 votes vote down vote up
public Object nullSafeGet(final ResultSet rs, final String[] names,
        final SessionImplementor session, final Object owner)
        throws HibernateException, SQLException {
    checkInitialization();
    final BigDecimal decimalMessage = rs.getBigDecimal(names[0]);
    if (rs.wasNull()) {
        return null;
    }
    final BigInteger message = 
        decimalMessage.setScale(0, BigDecimal.ROUND_UNNECESSARY).
            unscaledValue();
    return this.encryptor.decrypt(message);
}
 
Example 15
Source File: SQLTinyint.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** 
 * @see DataValueDescriptor#setValueFromResultSet 
 *
 * @exception SQLException		Thrown on error
 */
public void setValueFromResultSet(ResultSet resultSet, int colNumber,
								  boolean isNullable)
	throws SQLException
{
		value = resultSet.getByte(colNumber);
		isnull = (isNullable && resultSet.wasNull());
}
 
Example 16
Source File: SQLExtractor.java    From morpheus-core with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <V> V getValue(ResultSet rs, int colIndex) throws SQLException {
    final double value = rs.getDouble(colIndex);
    return rs.wasNull() ? null : (V)new Double(value);
}
 
Example 17
Source File: XMLBindingTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * Test serialization of the XML values inserted as part
 * XBindTestSetup processing.  For the documents that are
 * are larger than 32K, this tests that they can be correctly
 * read from disk as a stream (instead of just as as string).
 */
public void testXMLSerializeBinding() throws Exception
{
    // Array of expected character counts for every row inserted
    // into xTable.t1 as part of XBindTestSetup setup.  A "0"
    // means empty string; a "-1" means we inserted a null.
    int [] expectedCharCounts =
        new int [] { 40228, 38712, 1948, 1942, 1967, 1709, 22, -1, -1 };
    // GemStone changes BEGIN
    // results will be in unpredicatable order, so keep counts in
    // lists for later comparison.
    ArrayList<Integer> expectedCountsList = new ArrayList<Integer>(expectedCharCounts.length);
    ArrayList<Integer> actualCountsList = new ArrayList<Integer>();
    for (int i=0; i<expectedCharCounts.length; i++) {
      expectedCountsList.add(new Integer(expectedCharCounts[i]));
    }
    // GemStone changes END
    int rowCount = 0;
    ResultSet rs = createStatement().executeQuery(
            "select i, XMLSERIALIZE(X AS CLOB) FROM xTable.t1");

    while (rs.next())
    {
        int charCount;
        java.io.Reader xResult = rs.getCharacterStream(2);

        // Count the number of characters we read back.
        if (!rs.wasNull())
        {
            int ch = xResult.read();
            for (charCount = 0; ch != -1; ch = xResult.read())
            {
                /* Xalan serialization produces platform-specific line-
                 * endings (DERBY-2106), which can throw off the character
                 * count on Windows.  So if we see the Windows '\r' char
                 * we do not count it.
                 */
                if ((char)ch != '\r')
                    charCount++;
            }
            xResult.close();
        }
        else
            charCount = -1;

        // GemStone changes BEGIN
        actualCountsList.add(new Integer(charCount));
        //assertEquals("Unexpected serialized character count:",
        //    expectedCharCounts[rowCount], charCount);
        // GemStone changes END

        rowCount++;
    }

    assertEquals("Unexpected row count when serializing:",
        expectedCharCounts.length, rowCount);
    // GemStone changes BEGIN
    actualCountsList.removeAll(expectedCountsList);
    assertEquals(actualCountsList.size(), 0);
    // GemStone changes END

    /* Test binding to the XMLSERIALIZE operand.  Since
     * the operand is an XML value, and since we don't
     * allow binding to an XML value (which is tested in
     * testInvalidXMLBindings()), there's nothing more to
     * to do here.
     */
}
 
Example 18
Source File: SqlDialect.java    From morf with Apache License 2.0 4 votes vote down vote up
/**
 * Given an ordered list of columns and a {@link ResultSet}, creates a
 * {@link Record} from the current row.
 *
 * @param resultSet The {@link ResultSet}. Must have been advanced (using
 *          {@link ResultSet#next()}) to the appropriate row.
 * @param columns The columns, ordered according to their appearance in the
 *          {@link ResultSet}. Use {@link ResultSetMetadataSorter} to pre-sort
 *          your columns according to the {@link ResultSetMetaData} if you
 *          can't be sure that the SQL will return the columns in the precise
 *          order that you are expecting.
 * @return A {@link Record} representation of the current {@link ResultSet}
 *         row.
 */
public Record resultSetToRecord(ResultSet resultSet, Iterable<Column> columns) {

  // Provide initial sizing hint to the array. This potentially means double-traversal
  // of the columns if the column list is not a simple list, but it's almost certainly
  // worth it to minimise the array size and prevent resizing.
  RecordBuilder recordBuilder = DataSetUtils.record()
      .withInitialColumnCount(Iterables.size(columns));

  int idx = 1;
  for (Column column : columns) {
    try {
      switch (column.getType()) {
        case BIG_INTEGER:
          long longVal = resultSet.getLong(idx);
          if (resultSet.wasNull()) {
            recordBuilder.setObject(column.getName(), null);
          } else {
            recordBuilder.setLong(column.getName(), longVal);
          }
          break;
        case BOOLEAN:
          boolean boolVal = resultSet.getBoolean(idx);
          if (resultSet.wasNull()) {
            recordBuilder.setObject(column.getName(), null);
          } else {
            recordBuilder.setBoolean(column.getName(), boolVal);
          }
          break;
        case INTEGER:
          int intVal = resultSet.getInt(idx);
          if (resultSet.wasNull()) {
            recordBuilder.setObject(column.getName(), null);
          } else {
            recordBuilder.setInteger(column.getName(), intVal);
          }
          break;
        case DATE:
          Date date = resultSet.getDate(idx);
          if (date == null) {
            recordBuilder.setObject(column.getName(), null);
          } else {
            recordBuilder.setDate(column.getName(), date);
          }
          break;
        case DECIMAL:
          recordBuilder.setBigDecimal(column.getName(), resultSet.getBigDecimal(idx));
          break;
        case BLOB:
          recordBuilder.setByteArray(column.getName(), resultSet.getBytes(idx));
          break;
        case CLOB:
        case STRING:
          recordBuilder.setString(column.getName(), resultSet.getString(idx));
          break;
        default:
          recordBuilder.setObject(column.getName(), resultSet.getObject(idx));
          break;
      }
      idx++;
    } catch (SQLException e) {
      throw new RuntimeSqlException("Error retrieving value from result set with name [" + column.getName() + "]", e);
    }
  }
  return recordBuilder;
}
 
Example 19
Source File: SingleColumnByteArrayAttribute.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public Object readResultSet(ResultSet rs, int pos, DatabaseType databaseType, TimeZone timeZone) throws SQLException
{
    byte[] result = rs.getBytes(pos);
    if (rs.wasNull()) result = null;
    return result;
}
 
Example 20
Source File: DatabaseUtil.java    From presto with Apache License 2.0 4 votes vote down vote up
public static Long getBoxedLong(ResultSet rs, String name)
        throws SQLException
{
    long value = rs.getLong(name);
    return rs.wasNull() ? null : value;
}