Java Code Examples for java.sql.ResultSet.getShort()

The following are Jave code examples for showing how to use getShort() of the java.sql.ResultSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ChronoBike   File: SQLClauseSPInfo.java   View Source Code Vote up 6 votes
boolean fill(ResultSet rsProc)
{
	try
	{
		m_csCatalog = rsProc.getString("PROCEDURE_CAT");
		m_csName = rsProc.getString("PROCEDURE_NAME");
		m_csRemarks = rsProc.getString("REMARKS");
		m_sType = rsProc.getShort("PROCEDURE_TYPE");
		m_csSchem = rsProc.getString("PROCEDURE_SCHEM");
		return true;
	}
	catch(SQLException e)
	{
	}
	return false;
}
 
Example 2
Project: ChronoBike   File: StoredProcInfo.java   View Source Code Vote up 6 votes
boolean fill(ResultSet rsProc)
{
	try
	{
		m_csCatalog = rsProc.getString("PROCEDURE_CAT");
		m_csName = rsProc.getString("PROCEDURE_NAME");
		m_csRemarks = rsProc.getString("REMARKS");
		m_sType = rsProc.getShort("PROCEDURE_TYPE");
		m_csSchem = rsProc.getString("PROCEDURE_SCHEM");
		return true;
	}
	catch(SQLException e)
	{
	}
	return false;
}
 
Example 3
Project: scorekeeperfrontend   File: Challenge.java   View Source Code Vote up 5 votes
public Challenge(ResultSet rs) throws SQLException
{
	challengeid = (UUID)rs.getObject("challengeid");
	eventid     = (UUID)rs.getObject("eventid");
	name        = rs.getString("name");
	depth       = rs.getShort("depth");
}
 
Example 4
Project: openrouteservice   File: QueryColumnsInfo.java   View Source Code Vote up 5 votes
@SuppressWarnings("rawtypes")
public Object getType(int index, ResultSet resultSet) throws Exception
{
	Class type = _columns[index].getType();
	
	if (type == String.class)
	{
		String str = resultSet.getString(index + 1);
		if (!Helper.isEmpty(str))
			return str;
	}
	else if (type == Integer.class)
	{
		return resultSet.getInt(index + 1);
	}
	else if (type == Short.class)
	{
		return resultSet.getShort(index + 1);
	}
	else if (type == Long.class)
	{
		return resultSet.getLong(index + 1);
	}
	else if (type == Double.class)
	{
		return resultSet.getDouble(index + 1);
	}
	
	return null;
}
 
Example 5
Project: Lucid2.0   File: PlayerNPC.java   View Source Code Vote up 5 votes
public PlayerNPC(ResultSet rs) throws Exception {
    super(rs.getInt("ScriptId"), rs.getString("name"));
    hair = rs.getInt("hair");
    secondHair = hair;
    face = rs.getInt("face");
    secondFace = face;
    mapid = rs.getInt("map");
    skin = rs.getByte("skin");
    secondSkin = skin;
    charId = rs.getInt("charid");
    gender = rs.getByte("gender");
    secondGender = gender;
    job = rs.getShort("job");
    elf = rs.getInt("elf");
    faceMarking = rs.getInt("faceMarking");
    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) {
            pets[i] = Integer.parseInt(pet[i]);
        } else {
            pets[i] = 0;
        }
    }

    Connection con = DatabaseConnection.getConnection();
    try (PreparedStatement ps = con.prepareStatement("SELECT * FROM playernpcs_equip WHERE NpcId = ?")) {
        ps.setInt(1, getId());
        try (ResultSet rs2 = ps.executeQuery()) {
            while (rs2.next()) {
                equips.put(rs2.getByte("equippos"), rs2.getInt("equipid"));
                secondEquips.put(rs2.getByte("equippos"), rs2.getInt("equipid"));
            }
        }
    }
}
 
Example 6
Project: burstcoin   File: AT.java   View Source Code Vote up 5 votes
private static List<AT> createATs( ResultSet rs ) throws SQLException
{
	List<AT> ats = new ArrayList<AT>();
	while ( rs.next() )
	{
		int i = 0;
		Long atId = rs.getLong( ++i );
		Long creator = rs.getLong( ++i );
		String name = rs.getString( ++i );
		String description = rs.getString( ++i );
		short version = rs.getShort( ++i );
		byte[] stateBytes = decompressState(rs.getBytes( ++i ));
		int csize = rs.getInt( ++i );
		int dsize = rs.getInt( ++i );
		int c_user_stack_bytes = rs.getInt( ++i );
		int c_call_stack_bytes = rs.getInt( ++i );
		int creationBlockHeight = rs.getInt( ++i );
		int sleepBetween = rs.getInt( ++i );
		int nextHeight = rs.getInt( ++i );
		boolean freezeWhenSameBalance = rs.getBoolean( ++i );
		long minActivationAmount = rs.getLong(++i);
		byte[] ap_code = decompressState(rs.getBytes( ++i ));

		AT at = new AT( AT_API_Helper.getByteArray( atId ) , AT_API_Helper.getByteArray( creator ) , name , description , version ,
				stateBytes , csize , dsize , c_user_stack_bytes , c_call_stack_bytes , creationBlockHeight , sleepBetween , nextHeight ,
				freezeWhenSameBalance , minActivationAmount , ap_code );
		ats.add( at );

	}
	return ats;
}
 
Example 7
Project: jdbacl   File: JDBCDBImporter.java   View Source Code Vote up 5 votes
public void importPrimaryKeyOfTable(DBTable table, PKReceiver receiver) {
    LOGGER.debug("Importing primary keys for table '{}'", table);
    StopWatch watch = new StopWatch("importPrimaryKeyOfTable");
    ResultSet pkset = null;
    try {
     pkset = metaData.getPrimaryKeys(catalogName, schemaName, table.getName());
     TreeMap<Short, String> pkComponents = new TreeMap<Short, String>();
     String pkName = null;
     while (pkset.next()) {
     	String tableName = pkset.getString(3);
         if (!tableName.equals(table.getName())) // Bug fix for Firebird: 
         	continue;							// When querying X, it returns the pks of XY too
	
         String columnName = pkset.getString(4);
         short keySeq = pkset.getShort(5);
         pkComponents.put(keySeq, columnName);
         pkName = pkset.getString(6);
            LOGGER.debug("found pk column {}, {}, {}", new Object[] { columnName, keySeq, pkName });
     }
     if (pkComponents.size() > 0) {
      String[] columnNames = pkComponents.values().toArray(new String[pkComponents.size()]);
      receiver.receivePK(pkName, dialect.isDeterministicPKName(pkName), columnNames, table);
     }
    } catch (SQLException e) {
    	errorHandler.handleError("Error importing primary key of table " + table.getName());
    } finally {
    	DBUtil.close(pkset);
    }
    watch.stop();
}
 
Example 8
Project: ChronoBike   File: StoredProcParamDescBase.java   View Source Code Vote up 5 votes
public boolean fill(ResultSet rsParam)
{
	try
	{
		// Procedure identification
		m_colDescriptionInfo = new ColDescriptionInfo(); 
		m_csProcedureCatalog = rsParam.getString("PROCEDURE_CAT");
		m_csProcedureSchem = rsParam.getString("PROCEDURE_SCHEM");
		m_csProcedureName = rsParam.getString("PROCEDURE_NAME");
		
		// Kind of column / parameter
		m_sColType = rsParam.getShort("COLUMN_TYPE");
		
		m_colDescriptionInfo.m_csColName = rsParam.getString("COLUMN_NAME");
		m_colDescriptionInfo.m_nTypeId = rsParam.getInt("DATA_TYPE");
		m_colDescriptionInfo.m_nPrecision = rsParam.getInt("PRECISION");
		m_nLength = rsParam.getInt("LENGTH");
		
		m_sScale = rsParam.getShort("SCALE");
		m_sRadix = rsParam.getShort("RADIX");
		m_sNullable = rsParam.getShort("NULLABLE");
		m_csRemarks = rsParam.getString("REMARKS");
		
		return true;
	}
	catch(SQLException e)
	{
	}
	return false;
}
 
Example 9
Project: uavstack   File: DAOFactory.java   View Source Code Vote up 5 votes
public Object getResult(ResultSet rs, int columnIndex) throws SQLException {

            short s = rs.getShort(columnIndex);
            if (rs.wasNull()) {
                return null;
            }
            else {
                return new Short(s);
            }
        }
 
Example 10
Project: incubator-netbeans   File: JDBCTable.java   View Source Code Vote up 4 votes
protected void createIndexes() {
    Map<String, Index> newIndexes = new LinkedHashMap<String, Index>();
    try {
        ResultSet rs = MetadataUtilities.getIndexInfo(
                jdbcSchema.getJDBCCatalog().getJDBCMetadata().getDmd(),
                jdbcSchema.getJDBCCatalog().getName(), jdbcSchema.getName(),
                name, false, true);
        if (rs != null) {
            try {
                JDBCIndex index = null;
                String currentIndexName = null;
                while (rs.next()) {
                    // Ignore Indices marked statistic
                    // explicit: TYPE == DatabaseMetaData or
                    // implicit: ORDINAL_POSITION == 0
                    // @see java.sql.DatabaseMetaData#getIndexInfo
                    if (rs.getShort("TYPE") //NOI18N
                            == DatabaseMetaData.tableIndexStatistic
                            || rs.getInt("ORDINAL_POSITION") == 0) { //NOI18N
                        continue;
                    }

                    String indexName = MetadataUtilities.trimmed(rs.getString("INDEX_NAME")); //NOI18N
                    if (index == null || !(currentIndexName.equals(indexName))) {
                        index = createJDBCIndex(indexName, rs);
                        LOGGER.log(Level.FINE, "Created index {0}", index); //NOI18N

                        newIndexes.put(index.getName(), index.getIndex());
                        currentIndexName = indexName;
                    }

                    JDBCIndexColumn idx = createJDBCIndexColumn(index, rs);
                    if (idx == null) {
                        LOGGER.log(Level.INFO, "Cannot create index column for {0} from {1}",  //NOI18N
                                new Object[]{indexName, rs});
                    } else {
                        IndexColumn col = idx.getIndexColumn();
                        index.addColumn(col);
                        LOGGER.log(Level.FINE, "Added column {0} to index {1}",   //NOI18N
                                new Object[]{col.getName(), indexName});
                    }
                }
            } finally {
                rs.close();
            }
        }
    } catch (SQLException e) {
        filterSQLException(e);
    }

    indexes = Collections.unmodifiableMap(newIndexes);
}
 
Example 11
Project: calcite-avatica   File: JdbcResultSet.java   View Source Code Vote up 4 votes
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;
    }
    try {
      // Recursively extracts an Array using its ResultSet-representation
      return extractUsingResultSet(array, calendar);
    } catch (UnsupportedOperationException | SQLFeatureNotSupportedException e) {
      // Not every database might implement Array.getResultSet(). This call
      // assumes a non-nested array (depends on the db if that's a valid assumption)
      return extractUsingArray(array, calendar);
    }
  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 12
Project: jsf-core   File: ConvertableEnumTypeHandler.java   View Source Code Vote up 4 votes
@Override
protected Short getValue(ResultSet rs, int columnIndex)
        throws SQLException {
    return rs.getShort(columnIndex);
}
 
Example 13
Project: Lucid2.0   File: MapleShop.java   View Source Code Vote up 4 votes
public static MapleShop createFromDB(int id, boolean isShopId) {
    MapleShop ret = null;

    MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
    try {
        Connection con = DatabaseConnection.getConnection();
        PreparedStatement ps = con.prepareStatement(isShopId ? "SELECT * FROM shops WHERE shopid = ?" : "SELECT * FROM shops WHERE npcid = ?");
        int shopId;
        ps.setInt(1, id);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            shopId = rs.getInt("shopid");
            ret = new MapleShop(shopId, rs.getInt("npcid"));
            rs.close();
            ps.close();
        } else {
            rs.close();
            ps.close();
            return null;
        }
        ps = con.prepareStatement("SELECT * FROM shopitems WHERE shopid = ? ORDER BY position ASC");
        ps.setInt(1, shopId);
        rs = ps.executeQuery();
        List<Integer> recharges = new ArrayList<Integer>(rechargeableItems);
        while (rs.next()) {
            if (ii.itemExists(rs.getInt("itemid"))) {
                if ((GameConstants.isThrowingStar(rs.getInt("itemid"))) || (GameConstants.isBullet(rs.getInt("itemid")))) {
                    MapleShopItem starItem = new MapleShopItem((short) rs.getShort("buyable"), ii.getSlotMax(rs.getInt("itemid")), rs.getInt("itemid"), rs.getInt("price"), (short) rs.getInt("position"), rs.getInt("reqitem"), rs.getInt("reqitemq"), rs.getByte("rank"), rs.getInt("category"), rs.getInt("minLevel"), rs.getInt("expiration"), false);
                    ret.addItem(starItem);
                    if (rechargeableItems.contains(Integer.valueOf(starItem.getItemId()))) {
                        recharges.remove(Integer.valueOf(starItem.getItemId()));
                    }
                } else {
                    ret.addItem(new MapleShopItem((short) rs.getShort("buyable"), rs.getShort("quantity"), rs.getInt("itemid"), rs.getInt("price"), (short) rs.getInt("position"), rs.getInt("reqitem"), rs.getInt("reqitemq"), rs.getByte("rank"), rs.getInt("category"), rs.getInt("minLevel"), rs.getInt("expiration"), false)); //todo potential
                }
            }
        }
        for (Integer recharge : recharges) {
            ret.addItem(new MapleShopItem((short) 1, ii.getSlotMax(recharge.intValue()), recharge.intValue(), 0, (short) 0, 0, 0, (byte) 0, 0, 0, 0, false));
        }
        rs.close();
        ps.close();

        ps = con.prepareStatement("SELECT * FROM shopranks WHERE shopid = ? ORDER BY rank ASC");
        ps.setInt(1, shopId);
        rs = ps.executeQuery();
        while (rs.next()) {
            if (ii.itemExists(rs.getInt("itemid"))) {
                ret.ranks.add(new Pair<Integer, String>(Integer.valueOf(rs.getInt("itemid")), rs.getString("name")));
            }
        }
        rs.close();
        ps.close();
    } catch (SQLException e) {
        System.err.println("Could not load shop");
    }
    return ret;
}
 
Example 14
Project: tangyuan2   File: ShortTypeHandler.java   View Source Code Vote up 4 votes
@Override
public Short getNullableResult(ResultSet rs, String columnName) throws SQLException {
	return rs.getShort(columnName);
}
 
Example 15
Project: ralasafe   File: ResultSetReader.java   View Source Code Vote up 4 votes
public Object reader(ResultSet rs, int columnIndex) throws SQLException {
	return new Short(rs.getShort(columnIndex));
}
 
Example 16
Project: ralasafe   File: ResultSetReader.java   View Source Code Vote up 4 votes
public Object reader(ResultSet rs, String columnName)
		throws SQLException {
	return new Short(rs.getShort(columnName));
}
 
Example 17
Project: burstcoin   File: TransactionDb.java   View Source Code Vote up 4 votes
static TransactionImpl loadTransaction(Connection con, ResultSet rs) throws NxtException.ValidationException {
    try {

        byte type = rs.getByte("type");
        byte subtype = rs.getByte("subtype");
        int timestamp = rs.getInt("timestamp");
        short deadline = rs.getShort("deadline");
        byte[] senderPublicKey = rs.getBytes("sender_public_key");
        long amountNQT = rs.getLong("amount");
        long feeNQT = rs.getLong("fee");
        byte[] referencedTransactionFullHash = rs.getBytes("referenced_transaction_full_hash");
        int ecBlockHeight = rs.getInt("ec_block_height");
        long ecBlockId = rs.getLong("ec_block_id");
        byte[] signature = rs.getBytes("signature");
        long blockId = rs.getLong("block_id");
        int height = rs.getInt("height");
        long id = rs.getLong("id");
        long senderId = rs.getLong("sender_id");
        byte[] attachmentBytes = rs.getBytes("attachment_bytes");
        int blockTimestamp = rs.getInt("block_timestamp");
        byte[] fullHash = rs.getBytes("full_hash");
        byte version = rs.getByte("version");

        ByteBuffer buffer = null;
        if (attachmentBytes != null) {
            buffer = ByteBuffer.wrap(attachmentBytes);
            buffer.order(ByteOrder.LITTLE_ENDIAN);
        }

        TransactionType transactionType = TransactionType.findTransactionType(type, subtype);
        TransactionImpl.BuilderImpl builder = new TransactionImpl.BuilderImpl(version, senderPublicKey,
                amountNQT, feeNQT, timestamp, deadline,
                transactionType.parseAttachment(buffer, version))
                .referencedTransactionFullHash(referencedTransactionFullHash)
                .signature(signature)
                .blockId(blockId)
                .height(height)
                .id(id)
                .senderId(senderId)
                .blockTimestamp(blockTimestamp)
                .fullHash(fullHash);
        if (transactionType.hasRecipient()) {
            long recipientId = rs.getLong("recipient_id");
            if (! rs.wasNull()) {
                builder.recipientId(recipientId);
            }
        }
        if (rs.getBoolean("has_message")) {
            builder.message(new Appendix.Message(buffer, version));
        }
        if (rs.getBoolean("has_encrypted_message")) {
            builder.encryptedMessage(new Appendix.EncryptedMessage(buffer, version));
        }
        if (rs.getBoolean("has_public_key_announcement")) {
            builder.publicKeyAnnouncement(new Appendix.PublicKeyAnnouncement(buffer, version));
        }
        if (rs.getBoolean("has_encrypttoself_message")) {
            builder.encryptToSelfMessage(new Appendix.EncryptToSelfMessage(buffer, version));
        }
        if (version > 0) {
            builder.ecBlockHeight(ecBlockHeight);
            builder.ecBlockId(ecBlockId);
        }

        return builder.build();

    } catch (SQLException e) {
        throw new RuntimeException(e.toString(), e);
    }
}
 
Example 18
Project: jdbacl   File: JDBCDBImporter.java   View Source Code Vote up 4 votes
public void parseIndexSet(ResultSet indexSet, DBSchema schema, DBTable queriedTable, IndexReceiver receiver) throws SQLException {
       StopWatch watch = new StopWatch("parseIndexSet");
	OrderedNameMap<DBIndexInfo> indexes = new OrderedNameMap<DBIndexInfo>();
	while (indexSet.next()) {
	    String indexName = null;
	    try {
	    	String tableName = indexSet.getString(3);
	    	if (!tableSupported(tableName) || (queriedTable != null && !queriedTable.getName().equalsIgnoreCase(tableName)))
	    		continue; // table name is filtered out or a super string of the specified table name
	        boolean unique = !indexSet.getBoolean(4);
	        String indexCatalogName = indexSet.getString(5);
	        indexName = indexSet.getString(6);
	        short indexType = indexSet.getShort(7);
	        // not used: 
	        // tableIndexStatistic - this identifies table statistics that are returned in conjunction with a table's index descriptions
	        // tableIndexClustered - this is a clustered index
	        // tableIndexHashed - this is a hashed index
	        // tableIndexOther - this is some other style of index
	        //
	        short ordinalPosition = indexSet.getShort(8);
	        if (ordinalPosition == 0)
	            continue; // then indexType (7) is tableIndexStatistic 
	        String columnName = indexSet.getString(9);
	        String ascOrDesc = indexSet.getString(10);
	        Boolean ascending = (ascOrDesc != null ? ascOrDesc.charAt(0) == 'A' : null);
	        int cardinality = indexSet.getInt(11);
	        int pages = indexSet.getInt(12);
	        String filterCondition = indexSet.getString(13);
	        LOGGER.debug("found " + (unique ? "unique index " : "index ") + indexName + ", " 
	                    + indexCatalogName + ", " + indexType + ", " 
	                    + ordinalPosition + ", " + columnName + ", " + ascOrDesc + ", " 
	                    + cardinality + ", " + pages + ", " + filterCondition);
	        DBIndexInfo index = indexes.get(indexName);
	        if (index == null) {
	            index = new DBIndexInfo(indexName, tableName, indexType, indexCatalogName, unique,
	                ordinalPosition, columnName, ascending, cardinality, pages, filterCondition);
	            indexes.put(indexName, index);
	        } else {
	            index.addColumn(ordinalPosition, columnName);
	        }
	    } catch (Exception e) {
           	errorHandler.handleError("Error importing index " + indexName);
	    }
	}
	for (DBIndexInfo indexInfo : indexes.values()) {
		DBTable table = (queriedTable != null ? queriedTable : schema.getTable(indexInfo.tableName));
	    boolean deterministicName = dialect.isDeterministicIndexName(indexInfo.name);
	    receiver.receiveIndex(indexInfo, deterministicName, table, schema);
	}
	watch.stop();
}
 
Example 19
Project: calcite-avatica   File: ColumnMetaData.java   View Source Code Vote up 4 votes
/** Returns the value of a column of this type from a result set. */
public Object jdbcGet(ResultSet resultSet, int i) throws SQLException {
  switch (this) {
  case PRIMITIVE_BOOLEAN:
    return resultSet.getBoolean(i);
  case PRIMITIVE_BYTE:
    return resultSet.getByte(i);
  case PRIMITIVE_SHORT:
    return resultSet.getShort(i);
  case PRIMITIVE_INT:
    return resultSet.getInt(i);
  case PRIMITIVE_LONG:
    return resultSet.getLong(i);
  case PRIMITIVE_FLOAT:
    return resultSet.getFloat(i);
  case PRIMITIVE_DOUBLE:
    return resultSet.getDouble(i);
  case BOOLEAN:
    final boolean aBoolean = resultSet.getBoolean(i);
    return resultSet.wasNull() ? null : aBoolean;
  case BYTE:
    final byte aByte = resultSet.getByte(i);
    return resultSet.wasNull() ? null : aByte;
  case SHORT:
    final short aShort = resultSet.getShort(i);
    return resultSet.wasNull() ? null : aShort;
  case INTEGER:
    final int anInt = resultSet.getInt(i);
    return resultSet.wasNull() ? null : anInt;
  case LONG:
    final long aLong = resultSet.getLong(i);
    return resultSet.wasNull() ? null : aLong;
  case FLOAT:
    final float aFloat = resultSet.getFloat(i);
    return resultSet.wasNull() ? null : aFloat;
  case DOUBLE:
    final double aDouble = resultSet.getDouble(i);
    return resultSet.wasNull() ? null : aDouble;
  case JAVA_SQL_DATE:
    return resultSet.getDate(i);
  case JAVA_SQL_TIME:
    return resultSet.getTime(i);
  case JAVA_SQL_TIMESTAMP:
    return resultSet.getTimestamp(i);
  case ARRAY:
    return resultSet.getArray(i);
  case STRUCT:
    return resultSet.getObject(i, Struct.class);
  default:
    return resultSet.getObject(i);
  }
}
 
Example 20
Project: lams   File: IdentifierGeneratorHelper.java   View Source Code Vote up 4 votes
/**
 * Extract the value from the result set (which is assumed to already have been positioned to the apopriate row)
 * and wrp it in the appropriate Java numeric type.
 *
 * @param rs The result set from which to extract the value.
 * @param identifier The name of the identifier column
 * @param type The expected type of the value.
 *
 * @return The extracted value.
 *
 * @throws SQLException Indicates problems access the result set
 * @throws IdentifierGenerationException Indicates an unknown type.
 */
public static Serializable get(ResultSet rs, String identifier, Type type) throws SQLException, IdentifierGenerationException {
	if ( ResultSetIdentifierConsumer.class.isInstance( type ) ) {
		return ( ( ResultSetIdentifierConsumer ) type ).consumeIdentifier( rs );
	}
	if ( CustomType.class.isInstance( type ) ) {
		final CustomType customType = (CustomType) type;
		if ( ResultSetIdentifierConsumer.class.isInstance( customType.getUserType() ) ) {
			return ( (ResultSetIdentifierConsumer) customType.getUserType() ).consumeIdentifier( rs );
		}
	}

	Class clazz = type.getReturnedClass();
	if (rs.getMetaData().getColumnCount() == 1) {
		if ( clazz == Long.class ) {
			return rs.getLong( 1 );
		}
		else if ( clazz == Integer.class ) {
			return rs.getInt( 1 );
		}
		else if ( clazz == Short.class ) {
			return rs.getShort( 1 );
		}
		else if ( clazz == String.class ) {
			return rs.getString( 1 );
		}
		else if ( clazz == BigInteger.class ) {
			return rs.getBigDecimal( 1 ).setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
		}
		else if ( clazz == BigDecimal.class ) {
			return rs.getBigDecimal( 1 ).setScale( 0, BigDecimal.ROUND_UNNECESSARY );
		}
		else {
			throw new IdentifierGenerationException(
					"unrecognized id type : " + type.getName() + " -> " + clazz.getName()
			);
		}
	}
	else {
		if ( clazz == Long.class ) {
			return rs.getLong(identifier);
		}
		else if ( clazz == Integer.class ) {
			return rs.getInt(identifier);
		}
		else if ( clazz == Short.class ) {
			return rs.getShort(identifier);
		}
		else if ( clazz == String.class ) {
			return rs.getString(identifier);
		}
		else if ( clazz == BigInteger.class ) {
			return rs.getBigDecimal(identifier).setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
		}
		else if ( clazz == BigDecimal.class ) {
			return rs.getBigDecimal(identifier).setScale( 0, BigDecimal.ROUND_UNNECESSARY );
		}
		else {
			throw new IdentifierGenerationException(
					"unrecognized id type : " + type.getName() + " -> " + clazz.getName()
			);
		}
	}
}