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

The following examples show how to use java.sql.ResultSet#getByte() . 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: Utils.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public static String formatFullName(String nation, Connection conn, boolean fullName) throws SQLException {
	PreparedStatement statement = null;
	ResultSet result = null;
	try {
		statement = conn.prepareStatement("SELECT full_name, flag, alive, title from assembly.nation WHERE name = ?");
		statement.setString(1, sanitizeName(nation));
		result = statement.executeQuery();
		if (result.next()) {
			//Dead, return just full title
			if (result.getByte(3) != 1) {
				return result.getString(1);
			} else {
				return "<a href=\"//www.nationstates.net/nation=" + nation + "\"><img src=\"" + result.getString(2) + "\" class=\"miniflag\" alt=\"\" title=\"" + result.getString(1) + "\">" + (fullName ? result.getString(1) : result.getString(4)) + "</a>";
			}
		}
		return formatNationLink(nation);
	} finally {
		DbUtils.closeQuietly(result);
		DbUtils.closeQuietly(statement);
	}
}
 
Example 2
Source File: Utils.java    From NationStatesPlusPlus with MIT License 6 votes vote down vote up
public static String getRegionFlag(String region, Connection conn, String defaultFlag) throws SQLException {
	PreparedStatement statement = null;
	ResultSet result = null;
	try {
		statement = conn.prepareStatement("SELECT flag, alive FROM assembly.region WHERE name = ?");
		statement.setString(1, sanitizeName(region));
		result = statement.executeQuery();
		if (result.next()) {
			final String flag = result.getString(1);
			if (flag != null && !flag.trim().isEmpty()) {
				if (result.getByte(2) == 1) {
					return flag;
				}
				return "https://nationstatesplusplus.net/nationstates/static/exregion.png";
			}
		}
		return defaultFlag;
	} finally {
		DbUtils.closeQuietly(result);
		DbUtils.closeQuietly(statement);
	}
}
 
Example 3
Source File: MySQL5PlayerRegisteredItemsDAO.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
private HouseDecoration createDecoration(ResultSet rset) throws SQLException {
	int itemUniqueId = rset.getInt("item_unique_id");
	int itemId = rset.getInt("item_Id");
	byte floor = rset.getByte("floor");
	HouseDecoration decor = new HouseDecoration(itemUniqueId, itemId, floor);
	decor.setUsed(rset.getInt("owner_use_count") > 0);
	return decor;
}
 
Example 4
Source File: DataTypeUnsignedTest.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void byteMustFail(ResultSet rs) {
  try {
    rs.getByte(1);
    fail("getByte must have thrown error !");
  } catch (SQLException e) {
    assertEquals("22003", e.getSQLState());
  }
}
 
Example 5
Source File: DataTypeSignedTest.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void byteMustFail(ResultSet rs) {
  try {
    rs.getByte(1);
    fail("getByte must have thrown error !");
  } catch (SQLException e) {
    assertEquals("22003", e.getSQLState());
  }
}
 
Example 6
Source File: MySQL5PlayerBindPointDAO.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void loadBindPoint(Player player) {

	Connection con = null;
	try {
		con = DatabaseFactory.getConnection();
		PreparedStatement stmt = con.prepareStatement(SELECT_QUERY);
		stmt.setInt(1, player.getObjectId());
		ResultSet rset = stmt.executeQuery();
		if (rset.next()) {
			int mapId = rset.getInt("map_id");
			float x = rset.getFloat("x");
			float y = rset.getFloat("y");
			float z = rset.getFloat("z");
			byte heading = rset.getByte("heading");
			BindPointPosition bind = new BindPointPosition(mapId, x, y, z, heading);
			bind.setPersistentState(PersistentState.UPDATED);
			player.setBindPoint(bind);
		}
		rset.close();
		stmt.close();
	}
	catch (Exception e) {
		log.error("Could not restore BindPointPosition data for playerObjId: " + player.getObjectId() + " from DB: " + e.getMessage(), e);
	}
	finally {
		DatabaseFactory.close(con);
	}
}
 
Example 7
Source File: PlayerNPC.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
public PlayerNPC(ResultSet rs) throws Exception {
    super(rs.getInt("ScriptId"), rs.getString("name"));
    this.hair = rs.getInt("hair");
    this.face = rs.getInt("face");
    this.mapid = rs.getInt("map");
    this.skin = rs.getByte("skin");
    this.charId = rs.getInt("charid");
    this.gender = rs.getByte("gender");
    setCoords(rs.getInt("x"), rs.getInt("y"), rs.getInt("dir"), rs.getInt("Foothold"));
    String[] pet = rs.getString("pets").split(",");
    for (int i = 0; i < 3; i++) {
        if (pet[i] != null) {
            this.pets[i] = Integer.parseInt(pet[i]);
        } else {
            this.pets[i] = 0;
        }
    }

    Connection con = DatabaseConnection.getConnection();
    try (PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_equip WHERE NpcId = ?")) {
        ps.setInt(1, getId());
        ResultSet rs2 = ps.executeQuery();
        while (rs2.next()) {
            this.equips.put(rs2.getByte("equippos"), rs2.getInt("equipid"));
        }
        rs2.close();
        ps.close();
    }
}
 
Example 8
Source File: JdbcTypeUtil.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public static Object getRSData(ResultSet rs, String columnName, int jdbcType) throws SQLException {
    if (jdbcType == Types.BIT || jdbcType == Types.BOOLEAN) {
        return rs.getByte(columnName);
    } else {
        return rs.getObject(columnName);
    }
}
 
Example 9
Source File: ParameterMappingTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private void assertGetState(
    ResultSet rs,
    String colName,
    int getType,
    String expected) throws SQLException {

    try {
        switch (getType) {
        case XXX_BYTE:
            rs.getByte(colName);
            break;
        case XXX_SHORT:
            rs.getShort(colName);
                break;
        case XXX_INT:
            rs.getInt(colName);
            break;
        case XXX_LONG:
            rs.getLong(colName);
            break;
        case XXX_FLOAT:
            rs.getFloat(colName);
            break;
        case XXX_DOUBLE:
            rs.getDouble(colName);
            break;
        default:
            fail("wrong argument");
        }

        fail("exception expected");
    } catch (SQLException e) {
        println(e.toString());
        assertSQLState(expected, e);
    }
}
 
Example 10
Source File: JdbcTypeUtil.java    From canal with Apache License 2.0 5 votes vote down vote up
public static Object getRSData(ResultSet rs, String columnName, int jdbcType) throws SQLException {
    if (jdbcType == Types.BIT || jdbcType == Types.BOOLEAN) {
        return rs.getByte(columnName);
    } else {
        return rs.getObject(columnName);
    }
}
 
Example 11
Source File: BeanProcessor.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a {@code ResultSet} column into an object.  Simple
 * implementations could just call {@code rs.getObject(index)} while
 * more complex implementations could perform type manipulation to match
 * the column's type to the bean property type.
 *
 * <p>
 * This implementation calls the appropriate {@code ResultSet} getter
 * method for the given property type to perform the type conversion.  If
 * the property type doesn't match one of the supported
 * {@code ResultSet} types, {@code getObject} is called.
 * </p>
 *
 * @param rs The {@code ResultSet} currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 *
 * @param index The current column index being processed.
 *
 * @param propType The bean property type that this column needs to be
 * converted into.
 *
 * @throws SQLException if a database access error occurs
 *
 * @return The object from the {@code ResultSet} at the given column
 * index after optional type processing or {@code null} if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class propType)
    throws SQLException {

    if (propType.equals(String.class)) {
        return rs.getString(index);

    } else if (
        propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
        return rs.getInt(index);

    } else if (
        propType.equals(Boolean.TYPE) || propType.equals(Boolean.class)) {
        return rs.getBoolean(index);

    } else if (propType.equals(Long.TYPE) || propType.equals(Long.class)) {
        return rs.getLong(index);

    } else if (
        propType.equals(Double.TYPE) || propType.equals(Double.class)) {
        return rs.getDouble(index);

    } else if (
        propType.equals(Float.TYPE) || propType.equals(Float.class)) {
        return rs.getFloat(index);

    } else if (
        propType.equals(Short.TYPE) || propType.equals(Short.class)) {
        return rs.getShort(index);

    } else if (propType.equals(Byte.TYPE) || propType.equals(Byte.class)) {
        return rs.getByte(index);

    } else if (propType.equals(Timestamp.class)) {
        return rs.getTimestamp(index);

    } else {
        return rs.getObject(index);
    }
}
 
Example 12
Source File: BooleansOnNumericColumnsIqResultSetComparator.java    From reladomo with Apache License 2.0 4 votes vote down vote up
public Object createObjectFrom(ResultSet rs) throws SQLException
{
    BooleansOnNumericColumnsIqData data = new BooleansOnNumericColumnsIqData();
    data.setId(rs.getInt(1));
    data.setBooleanValue(rs.getInt(2) == 1);
    data.setBooleanOnByteValue(rs.getByte(3) == 1);
    data.setBooleanOnShortValue(rs.getShort(4) == 1);
    data.setBooleanOnIntValue(rs.getInt(5) == 1);
    data.setBooleanOnLongValue(rs.getLong(6) == 1);

    int ib = rs.getInt(7);
    if(rs.wasNull())
    {
        data.setNullableBooleanValueNull();
    }
    else
    {
        data.setNullableBooleanValue(ib == 1);
    }

    byte b = rs.getByte(8);
    if(rs.wasNull())
    {
        data.setNullableBooleanOnByteValueNull();
    }
    else
    {
        data.setNullableBooleanOnByteValue(b == 1);
    }

    short st = rs.getShort(9);
    if(rs.wasNull())
    {
        data.setNullableBooleanOnShortValueNull();
    }
    else
    {
        data.setNullableBooleanOnShortValue(st == 1);
    }

    int it = rs.getInt(10);
    if(rs.wasNull())
    {
        data.setNullableBooleanOnIntValueNull();
    }
    else
    {
        data.setNullableBooleanOnIntValue(it == 1);
    }

    long lt = rs.getLong(11);
    if(rs.wasNull())
    {
        data.setNullableBooleanOnLongValueNull();
    }
    else
    {
        data.setNullableBooleanOnLongValue(lt == 1);
    }

    BooleansOnNumericColumnsIq booleansOnNumericColumnsIq = new BooleansOnNumericColumnsIq();
    booleansOnNumericColumnsIq.zSetNonTxData(data);
    return booleansOnNumericColumnsIq;
}
 
Example 13
Source File: ResultSets.java    From sqlhelper with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Retrieve a JDBC column value from a ResultSet, using the specified value type.
 * <p>Uses the specifically typed ResultSet accessor methods, falling back to
 * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types.
 * <p>Note that the returned value may not be assignable to the specified
 * required type, in case of an unknown type. Calling code needs to deal
 * with this case appropriately, e.g. throwing a corresponding exception.
 *
 * @param rs           is the ResultSet holding the data
 * @param index        is the column index
 * @param requiredType the required value type (may be {@code null})
 * @return the value object (possibly not of the specified required type,
 * with further conversion steps necessary)
 * @throws SQLException if thrown by the JDBC API
 * @see #getResultSetValue(ResultSet, int)
 */
@Nullable
public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType) throws SQLException {
    if (requiredType == null) {
        return getResultSetValue(rs, index);
    }

    Object value;

    // Explicitly extract typed value, as far as possible.
    if (String.class == requiredType) {
        return rs.getString(index);
    } else if (boolean.class == requiredType || Boolean.class == requiredType) {
        value = rs.getBoolean(index);
    } else if (byte.class == requiredType || Byte.class == requiredType) {
        value = rs.getByte(index);
    } else if (short.class == requiredType || Short.class == requiredType) {
        value = rs.getShort(index);
    } else if (int.class == requiredType || Integer.class == requiredType) {
        value = rs.getInt(index);
    } else if (long.class == requiredType || Long.class == requiredType) {
        value = rs.getLong(index);
    } else if (float.class == requiredType || Float.class == requiredType) {
        value = rs.getFloat(index);
    } else if (double.class == requiredType || Double.class == requiredType ||
            Number.class == requiredType) {
        value = rs.getDouble(index);
    } else if (BigDecimal.class == requiredType) {
        return rs.getBigDecimal(index);
    } else if (java.sql.Date.class == requiredType) {
        return rs.getDate(index);
    } else if (java.sql.Time.class == requiredType) {
        return rs.getTime(index);
    } else if (java.sql.Timestamp.class == requiredType || java.util.Date.class == requiredType) {
        return rs.getTimestamp(index);
    } else if (byte[].class == requiredType) {
        return rs.getBytes(index);
    } else if (Blob.class == requiredType) {
        return rs.getBlob(index);
    } else if (Clob.class == requiredType) {
        return rs.getClob(index);
    } else if (requiredType.isEnum()) {
        // Enums can either be represented through a String or an enum index value:
        // leave enum type conversion up to the caller (e.g. a ConversionService)
        // but make sure that we return nothing other than a String or an Integer.
        Object obj = rs.getObject(index);
        if (obj instanceof String) {
            return obj;
        } else if (obj instanceof Number) {
            // Defensively convert any Number to an Integer (as needed by our
            // ConversionService's IntegerToEnumConverterFactory) for use as index
            return Numbers.convertNumberToTargetClass((Number) obj, Integer.class);
        } else {
            // e.g. on Postgres: getObject returns a PGObject but we need a String
            return rs.getString(index);
        }
    } else {
        // Some unknown type desired -> rely on getObject.
        try {
            return Reflects.invokeAnyMethod(rs, "getObject", new Class[]{int.class, Class.class}, new Object[]{index, requiredType}, false, true);
            // return rs.getObject(index, requiredType);
        } catch (AbstractMethodError err) {
            logger.warn("JDBC driver does not implement JDBC 4.1 'getObject(int, Class)' method", err);
        } catch (Throwable ex) {
            logger.warn("JDBC driver has limited support for JDBC 4.1 'getObject(int, Class)' method", ex);
        }

        // Corresponding SQL types for JSR-310 / Joda-Time types, left up
        // to the caller to convert them (e.g. through a ConversionService).
        String typeName = requiredType.getSimpleName();
        if ("LocalDate".equals(typeName)) {
            return rs.getDate(index);
        } else if ("LocalTime".equals(typeName)) {
            return rs.getTime(index);
        } else if ("LocalDateTime".equals(typeName)) {
            return rs.getTimestamp(index);
        }

        // Fall back to getObject without type specification, again
        // left up to the caller to convert the value if necessary.
        return getResultSetValue(rs, index);
    }

    // Perform was-null check if necessary (for results that the JDBC driver returns as primitives).
    return (rs.wasNull() ? null : value);
}
 
Example 14
Source File: MapperUtils.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 在rs中获取column字段的typeClass型的值
 *
 * @param rs
 * @param column
 * @param paramClass
 *
 * @return
 *
 * @throws SQLException
 */
public static Object getValue4Type(ResultSet rs, String column, Class<?> typeClass) throws SQLException {

    if (Collection.class.isAssignableFrom(typeClass)) {
        return null;
    }

    try {
        rs.findColumn(column);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    if (typeClass.equals(Integer.class) || typeClass.equals(Integer.TYPE)) {
        return rs.getInt(column);
    }

    if (typeClass.equals(Long.class) || typeClass.equals(Long.TYPE)) {
        return rs.getLong(column);
    }

    if (typeClass.equals(Boolean.class) || typeClass.equals(Boolean.TYPE)) {
        return rs.getBoolean(column);
    }

    if (typeClass.equals(Float.class) || typeClass.equals(Float.TYPE)) {
        return rs.getFloat(column);
    }

    if (typeClass.equals(Double.class) || typeClass.equals(Double.TYPE)) {
        return rs.getDouble(column);
    }

    if (typeClass.equals(Byte.class) || typeClass.equals(Byte.TYPE)) {
        return rs.getByte(column);
    }

    if (typeClass.equals(String.class)) {
        return rs.getString(column);
    }

    if (Date.class.isAssignableFrom(typeClass)) {
        return rs.getTimestamp(column);
    }

    if (java.sql.Date.class.isAssignableFrom(typeClass)) {
        return rs.getDate(column);
    }

    return rs.getObject(column);
}
 
Example 15
Source File: MsSqlChange.java    From kafka-connect-cdc-mssql with Apache License 2.0 4 votes vote down vote up
public MsSqlChange build(TableMetadataProvider.TableMetadata tableMetadata, ResultSet resultSet, Time time) throws SQLException {
  MsSqlChange change = new MsSqlChange();
  change.timestamp = time.milliseconds();
  change.databaseName = tableMetadata.databaseName();
  change.schemaName = tableMetadata.schemaName();
  change.tableName = tableMetadata.tableName();

  final long sysChangeVersion = resultSet.getLong("__metadata_sys_change_version");
  final long sysChangeCreationVersion = resultSet.getLong("__metadata_sys_change_creation_version");
  final String changeOperation = resultSet.getString("__metadata_sys_change_operation");

  change.metadata = ImmutableMap.of(
      "sys_change_operation", changeOperation,
      "sys_change_creation_version", String.valueOf(sysChangeCreationVersion),
      "sys_change_version", String.valueOf(sysChangeVersion)
  );

  switch (changeOperation) {
    case "I":
      change.changeType = ChangeType.INSERT;
      break;
    case "U":
      change.changeType = ChangeType.UPDATE;
      break;
    case "D":
      change.changeType = ChangeType.DELETE;
      break;
    default:
      throw new UnsupportedOperationException(
          String.format("Unsupported sys_change_operation of '%s'", changeOperation)
      );
  }
  log.trace("build() - changeType = {}", change.changeType);

  change.keyColumns = new ArrayList<>(tableMetadata.keyColumns().size());
  change.valueColumns = new ArrayList<>(tableMetadata.columnSchemas().size());

  for (Map.Entry<String, Schema> kvp : tableMetadata.columnSchemas().entrySet()) {
    String columnName = kvp.getKey();
    Schema schema = kvp.getValue();
    Object value;
    if (Schema.Type.INT8 == schema.type()) {
      // Really lame Microsoft. A tiny int is stored as a single byte with a value of 0-255.
      // Explain how this should be returned as a short?
      value = resultSet.getByte(columnName);
    } else if (Schema.Type.INT32 == schema.type() &&
        Date.LOGICAL_NAME.equals(schema.name())) {
      value = new java.util.Date(
          resultSet.getDate(columnName, calendar).getTime()
      );
    } else if (Schema.Type.INT32 == schema.type() &&
        org.apache.kafka.connect.data.Time.LOGICAL_NAME.equals(schema.name())) {
      value = new java.util.Date(
          resultSet.getTime(columnName, calendar).getTime()
      );
    } else {
      value = resultSet.getObject(columnName);
    }

    log.trace("build() - columnName = '{}' value = '{}'", columnName, value);
    MsSqlColumnValue columnValue = new MsSqlColumnValue(columnName, schema, value);
    change.valueColumns.add(columnValue);
    if (tableMetadata.keyColumns().contains(columnName)) {
      change.keyColumns.add(columnValue);
    }
  }

  return change;
}
 
Example 16
Source File: QuarkMetaResultSet.java    From quark with Apache License 2.0 4 votes vote down vote up
private static Object getValue(ResultSet resultSet, int type, int j,
                               Calendar calendar) throws SQLException {
  switch (type) {
    case Types.BIGINT:
      final long aLong = resultSet.getLong(j + 1);
      return aLong == 0 && resultSet.wasNull() ? null : aLong;
    case Types.INTEGER:
      final int anInt = resultSet.getInt(j + 1);
      return anInt == 0 && resultSet.wasNull() ? null : anInt;
    case Types.SMALLINT:
      final short aShort = resultSet.getShort(j + 1);
      return aShort == 0 && resultSet.wasNull() ? null : aShort;
    case Types.TINYINT:
      final byte aByte = resultSet.getByte(j + 1);
      return aByte == 0 && resultSet.wasNull() ? null : aByte;
    case Types.DOUBLE:
    case Types.FLOAT:
      final double aDouble = resultSet.getDouble(j + 1);
      return aDouble == 0D && resultSet.wasNull() ? null : aDouble;
    case Types.REAL:
      final float aFloat = resultSet.getFloat(j + 1);
      return aFloat == 0D && resultSet.wasNull() ? null : aFloat;
    case Types.DATE:
      final Date aDate = resultSet.getDate(j + 1, calendar);
      return aDate == null
          ? null
          : (int) (aDate.getTime() / DateTimeUtils.MILLIS_PER_DAY);
    case Types.TIME:
      final Time aTime = resultSet.getTime(j + 1, calendar);
      return aTime == null
          ? null
          : (int) (aTime.getTime() % DateTimeUtils.MILLIS_PER_DAY);
    case Types.TIMESTAMP:
      final Timestamp aTimestamp = resultSet.getTimestamp(j + 1, calendar);
      return aTimestamp == null ? null : aTimestamp.getTime();
    case Types.ARRAY:
      final Array array = resultSet.getArray(j + 1);
      if (null == array) {
        return null;
      }
      ResultSet arrayValues = array.getResultSet();
      TreeMap<Integer, Object> map = new TreeMap<>();
      while (arrayValues.next()) {
        // column 1 is the index in the array, column 2 is the value.
        // Recurse on `getValue` to unwrap nested types correctly.
        // `j` is zero-indexed and incremented for us, thus we have `1` being used twice.
        map.put(arrayValues.getInt(1), getValue(arrayValues, array.getBaseType(), 1, calendar));
      }
      // If the result set is not in the same order as the actual Array, TreeMap fixes that.
      // Need to make a concrete list to ensure Jackson serialization.
      //return new ListLike<Object>(new ArrayList<>(map.values()), ListLikeType.ARRAY);
      return new ArrayList<>(map.values());
    case Types.STRUCT:
      Struct struct = resultSet.getObject(j + 1, Struct.class);
      Object[] attrs = struct.getAttributes();
      List<Object> list = new ArrayList<>(attrs.length);
      for (Object o : attrs) {
        list.add(o);
      }
      return list;
    default:
      return resultSet.getObject(j + 1);
  }
}
 
Example 17
Source File: JdbcPOJOInputOperator.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object getTuple(ResultSet result)
{
  Object obj;
  try {
    obj = pojoClass.newInstance();
  } catch (InstantiationException | IllegalAccessException ex) {
    store.disconnect();
    throw new RuntimeException(ex);
  }

  try {
    for (int i = 0; i < fieldInfos.size(); i++) {
      int type = columnDataTypes.get(i);
      ActiveFieldInfo afi = columnFieldSetters.get(i);

      switch (type) {
        case Types.CHAR:
        case Types.VARCHAR:
          String strVal = result.getString(i + 1);
          ((PojoUtils.Setter<Object, String>)afi.setterOrGetter).set(obj, strVal);
          break;

        case Types.BOOLEAN:
          boolean boolVal = result.getBoolean(i + 1);
          ((PojoUtils.SetterBoolean<Object>)afi.setterOrGetter).set(obj, boolVal);
          break;

        case Types.TINYINT:
          byte byteVal = result.getByte(i + 1);
          ((PojoUtils.SetterByte<Object>)afi.setterOrGetter).set(obj, byteVal);
          break;

        case Types.SMALLINT:
          short shortVal = result.getShort(i + 1);
          ((PojoUtils.SetterShort<Object>)afi.setterOrGetter).set(obj, shortVal);
          break;

        case Types.INTEGER:
          int intVal = result.getInt(i + 1);
          ((PojoUtils.SetterInt<Object>)afi.setterOrGetter).set(obj, intVal);
          break;

        case Types.BIGINT:
          long longVal = result.getLong(i + 1);
          ((PojoUtils.SetterLong<Object>)afi.setterOrGetter).set(obj, longVal);
          break;

        case Types.FLOAT:
          float floatVal = result.getFloat(i + 1);
          ((PojoUtils.SetterFloat<Object>)afi.setterOrGetter).set(obj, floatVal);
          break;

        case Types.DOUBLE:
          double doubleVal = result.getDouble(i + 1);
          ((PojoUtils.SetterDouble<Object>)afi.setterOrGetter).set(obj, doubleVal);
          break;

        case Types.DECIMAL:
          BigDecimal bdVal = result.getBigDecimal(i + 1);
          ((PojoUtils.Setter<Object, BigDecimal>)afi.setterOrGetter).set(obj, bdVal);
          break;

        case Types.TIMESTAMP:
          Timestamp tsVal = result.getTimestamp(i + 1);
          ((PojoUtils.Setter<Object, Timestamp>)afi.setterOrGetter).set(obj, tsVal);
          break;

        case Types.TIME:
          Time timeVal = result.getTime(i + 1);
          ((PojoUtils.Setter<Object, Time>)afi.setterOrGetter).set(obj, timeVal);
          break;

        case Types.DATE:
          Date dateVal = result.getDate(i + 1);
          ((PojoUtils.Setter<Object, Date>)afi.setterOrGetter).set(obj, dateVal);
          break;

        default:
          handleUnknownDataType(type, obj, afi);
          break;
      }
    }
    return obj;
  } catch (SQLException e) {
    store.disconnect();
    throw new RuntimeException("fetching metadata", e);
  }
}
 
Example 18
Source File: JdbcUtils.java    From pinlater with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve a JDBC column value from a ResultSet. To avoid NullPointerException, this method
 * doesn't support primitive type.
 *
 * @param rs           the result set.
 * @param index        the index of column to retrieve the value for.
 * @param expectedType the expected type for the column of the given index in the resultset.
 * @return the value in the resultset for the given column.
 * @throws SQLException
 */
public static Object getResultSetValue(
    ResultSet rs, int index, Class expectedType) throws SQLException {
  if (expectedType == null) {
    throw new IllegalArgumentException("requiredType cannot be null");
  }

  Object value;
  boolean wasNullCheck = false;

  if (String.class.equals(expectedType)) {
    value = new String(rs.getBytes(index), Charsets.UTF_8);
  } else if (Boolean.class.equals(expectedType)) {
    value = rs.getBoolean(index);
    wasNullCheck = true;
  } else if (Byte.class.equals(expectedType)) {
    value = rs.getByte(index);
    wasNullCheck = true;
  } else if (Short.class.equals(expectedType)) {
    value = rs.getShort(index);
    wasNullCheck = true;
  } else if (Integer.class.equals(expectedType)) {
    value = rs.getInt(index);
    wasNullCheck = true;
  } else if (Long.class.equals(expectedType)) {
    value = rs.getLong(index);
    wasNullCheck = true;
  } else if (Float.class.equals(expectedType)) {
    value = rs.getFloat(index);
    wasNullCheck = true;
  } else if (Double.class.equals(expectedType)
      || Number.class.equals(expectedType)) {
    value = rs.getDouble(index);
    wasNullCheck = true;
  } else if (byte[].class.equals(expectedType)) {
    value = rs.getBytes(index);
  } else if (java.sql.Timestamp.class.equals(expectedType)
      || java.util.Date.class.equals(expectedType)) {
    value = rs.getTimestamp(index);
  } else if (BigDecimal.class.equals(expectedType)) {
    value = rs.getBigDecimal(index);
  } else if (InputStream.class.equals(expectedType)) {
    value = rs.getBinaryStream(index);
  } else {
    throw new IllegalArgumentException(
        String.format("Unsupported expected type: %s", expectedType.getName()));
  }

  // Perform was-null check if demanded (for results that the JDBC driver returns as primitives).
  if (wasNullCheck && value != null && rs.wasNull()) {
    value = null;
  }
  return value;
}
 
Example 19
Source File: ByteResultSetGetter.java    From SimpleFlatMapper with MIT License 4 votes vote down vote up
@Override
public byte getByte(final ResultSet target) throws SQLException {
	return target.getByte(column);
}
 
Example 20
Source File: ByteTypeHandler.java    From mybaties with Apache License 2.0 4 votes vote down vote up
@Override
public Byte getNullableResult(ResultSet rs, int columnIndex)
    throws SQLException {
  return rs.getByte(columnIndex);
}