Java Code Examples for java.sql.ResultSet#getShort()
The following examples show how to use
java.sql.ResultSet#getShort() .
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: MySQLProcedure.java From netbeans with Apache License 2.0 | 6 votes |
/** * A "special" version because MySQL returns character lengths in * the precision column instead of the length column - sheesh. * * Logged as a MySQL bug - http://bugs.mysql.com/bug.php?id=41269 * When this is fixed this workaround will need to be backed out. */ private static JDBCValue createValue(ResultSet rs, MetadataElement parent) throws SQLException { String name = rs.getString("COLUMN_NAME"); int length = 0; int precision = 0; SQLType type = JDBCUtils.getSQLType(rs.getInt("DATA_TYPE")); String typeName = rs.getString("TYPE_NAME"); if (JDBCUtils.isNumericType(type)) { precision = rs.getInt("PRECISION"); } else { length = rs.getInt("PRECISION"); } short scale = rs.getShort("SCALE"); short radix = rs.getShort("RADIX"); Nullable nullable = JDBCUtils.getProcedureNullable(rs.getShort("NULLABLE")); return new JDBCValue(parent, name, type, typeName, length, precision, radix, scale, nullable); }
Example 2
Source File: ConcurrentConnTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
public static void getPrimaryKeys(DatabaseMetaData dmd, String tablePattern,PrintStream out) throws SQLException { ResultSet rs = dmd.getPrimaryKeys(null, null, tablePattern); while (rs.next()) { // 1.TABLE_CAT String => table catalog (may be null) String tableCat = rs.getString(1); // 2.TABLE_SCHEM String => table schema (may be null) String tableSchem = rs.getString(2); // 3.TABLE_NAME String => table name String tableName = rs.getString(3); // 4.COLUMN_NAME String => column name String columnName = rs.getString(4); // 5.KEY_SEQ short => sequence number within primary key short keySeq = rs.getShort(5); // 6.PK_NAME String => primary key name (may be null) String pkName = rs.getString(6); } rs.close(); }
Example 3
Source File: JdbcBroker.java From geoportal-server-harvester with Apache License 2.0 | 6 votes |
private <T> T readValue(ResultSet r, String columnName, Class<T> clazz) throws SQLException { switch (clazz.getSimpleName()) { case "String": return (T)(r.getString(columnName)); case "Double": return (T)(new Double(r.getDouble(columnName))); case "Float": return (T)(new Float(r.getFloat(columnName))); case "Long": return (T)(new Long(r.getLong(columnName))); case "Integer": return (T)(new Integer(r.getInt(columnName))); case "Short": return (T)(new Integer(r.getShort(columnName))); case "BigDecimal": return (T)(r.getBigDecimal(columnName)); case "Boolean": return (T)(new Boolean(r.getBoolean(columnName))); } return null; }
Example 4
Source File: ArrayShortResultSetGetter.java From SimpleFlatMapper with MIT License | 5 votes |
@Override public short[] get(ResultSet target) throws Exception { Array sqlArray = target.getArray(index); if (sqlArray != null) { short[] array = INIT; int capacity = 0; int size = 0; ResultSet rs = sqlArray.getResultSet(); try { while(rs.next()) { if (size >= capacity) { int newCapacity = Math.max(Math.max(capacity+ 1, capacity + (capacity >> 1)), 10); array = Arrays.copyOf(array, newCapacity); capacity = newCapacity; } array[size++] = rs.getShort(VALUE_INDEX); } } finally { rs.close(); } return Arrays.copyOf(array, size); } return null; }
Example 5
Source File: SQLSmallint.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * @see DataValueDescriptor#setValueFromResultSet * * @exception SQLException Thrown on error */ public void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable) throws SQLException { try { value = resultSet.getShort(colNumber); isnull = (isNullable && resultSet.wasNull()); } catch (SQLException selq) { int i = resultSet.getInt(colNumber); value = (short) i; isnull = false; } }
Example 6
Source File: TableMetadata.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
private void initIndexes(DatabaseMetaData meta) throws SQLException { ResultSet rs = null; try { rs = meta.getIndexInfo(catalog, schema, name, false, true); while ( rs.next() ) { if ( rs.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic ) continue; addIndex(rs); } } finally { if (rs != null) rs.close(); } }
Example 7
Source File: GroupsQueryImpl.java From ade with GNU General Public License v3.0 | 5 votes |
/** * Helper method for parsing the group results from a ResultSet object. * @param resultSet contains the group information from a SQL Query. * @return Group object with the results from the resultSet. * @throws SQLException * @throws AdeInternalException */ private Group parseGroupResult(ResultSet resultSet) throws SQLException, AdeInternalException { int uid = resultSet.getInt("GROUP_INTERNAL_ID"); String name = resultSet.getString("GROUP_NAME"); Short groupTypeVal = resultSet.getShort("GROUP_TYPE"); GroupType groupType = GroupType.getGroupType(groupTypeVal); Short dataTypeVal = resultSet.getShort("DATA_TYPE"); DataType dataType = DataType.getDataType(dataTypeVal); short evaluationOrder = resultSet.getShort("EVALUATION_ORDER"); int rid = resultSet.getInt("RULE_INTERNAL_ID"); String ruleName = getRuleName(rid); return new Group(uid,name,groupType,dataType,evaluationOrder,ruleName); }
Example 8
Source File: JdbcDebugUtil.java From XPagesExtensionLibrary with Apache License 2.0 | 5 votes |
private static Object getColumnValue( ResultSet resultSet, ResultSetMetaData meta, int col ) throws SQLException { int type = meta.getColumnType(col); switch( type ) { case Types.BIT: return new Boolean(resultSet.getBoolean(col)); case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return resultSet.getString(col); case Types.TINYINT: case Types.SMALLINT: return new Short(resultSet.getShort(col)); case Types.INTEGER: return new Integer(resultSet.getInt(col)); case Types.BIGINT: return new Long(resultSet.getLong(col)); case Types.NUMERIC: if( meta.getScale(col)>0 ) { return new Double(resultSet.getDouble(col)); } if( meta.getPrecision(col)>=9 ) { return new Long(resultSet.getLong(col)); } return new Integer(resultSet.getInt(col)); case Types.FLOAT: return new Float(resultSet.getFloat(col)); case Types.DOUBLE: case Types.REAL: case Types.DECIMAL: return new Double(resultSet.getDouble(col)); } throw new SQLException( StringUtil.format("Data type not yet handled ({0})", StringUtil.toString(type)) ); // $NLX-JdbcDebugUtil.Datatypenotyethandled0-1$ }
Example 9
Source File: TPCETradeResult.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
protected void invokeFrame4() throws SQLException { String s_ex_id; short c_tier; //select //s_ex_id = S_EX_ID, //s_name //= S_NAME //from //SECURITY //where //S_SYMB = symbol PreparedStatement ps= conn.prepareStatement(selectSecurity); ps.setString(1, symbol); ResultSet rs = ps.executeQuery(); if (rs.next()) { s_ex_id = rs.getString("S_EX_ID"); s_name = rs.getString(2); //S_NAME if (logDML) Log.getLogWriter().info(selectSecurity + " gets S_EX_ID: " + s_ex_id + " S_NAME: " + s_name + " for S_SYMB = " + symbol); if (rs.next()) { throw new TestException ( selectTaxRate + " has more than 1 row " + "in result set for S_SYMB = " + symbol); } } else { throw new TestException ( selectTaxRate + " does not get single row " + "in result set for S_SYMB = " + symbol); } rs.close(); ps.close(); //select //c_tier = C_TIER //from //CUSTOMER //where //C_ID = cust_id ps= conn.prepareStatement(selectCustomer); ps.setLong(1, cust_id); rs = ps.executeQuery(); if (rs.next()) { c_tier = rs.getShort("C_TIER"); if (logDML) Log.getLogWriter().info(selectCustomer + " gets C_TIER: " + c_tier + " S_NAME: " + s_name + " for C_ID = " + cust_id); if (rs.next()) { throw new TestException (selectCustomer + " has more than 1 row " + "in result set for C_ID = " + cust_id); } } else { throw new TestException (selectCustomer + " does not get single row " + "in result set for C_ID = " + cust_id); } rs.close(); ps.close(); // Only want 1 commission rate row //select first 1 row //comm_rate = CR_RATE //from //COMMISSION_RATE //where //CR_C_TIER = c_tier and //CR_TT_ID = type_id and //CR_EX_ID = s_ex_id and //CR_FROM_QTY <= trade_qty and //CR_TO_QTY >= trade_qty ps= conn.prepareStatement(selectCommRate); ps.setShort(1, c_tier); ps.setString(2, type_id); ps.setString(3, s_ex_id); ps.setInt(4, trade_qty); ps.setInt(5, trade_qty); rs = ps.executeQuery(); if (rs.next()) { comm_rate = rs.getBigDecimal("CR_RATE"); if (logDML) Log.getLogWriter().info(selectCommRate + " gets CR_RATE: " + comm_rate + " for CR_C_TIER = " + c_tier + " CR_TT_ID = " + type_id + " CR_EX_ID = " + s_ex_id + " CR_FROM_QTY <= " + trade_qty + " CR_TO_QTY >= " + trade_qty); if (rs.next()) { throw new TestException (selectCommRate + " has more than 1 row " + "in result set for CR_C_TIER = " + c_tier + " CR_TT_ID = " + type_id + " CR_EX_ID = " + s_ex_id + " CR_FROM_QTY <= " + trade_qty + " CR_TO_QTY >= " + trade_qty); } } else { throw new TestException (selectCommRate + " does not get single row " + "in result set for CR_C_TIER = " + c_tier + " CR_TT_ID = " + type_id + " CR_EX_ID = " + s_ex_id + " CR_FROM_QTY <= " + trade_qty + " CR_TO_QTY >= " + trade_qty); } rs.close(); ps.close(); }
Example 10
Source File: ProfileConfigDAO.java From micro-integrator with Apache License 2.0 | 4 votes |
public Map<String, ProfileConfiguration> loadProfileConfigs() throws UserStoreException { Connection dbConnection = null; Map<String, ProfileConfiguration> map = new HashMap<String, ProfileConfiguration>(); PreparedStatement prepStmt = null; try { dbConnection = dataSource.getConnection(); prepStmt = dbConnection .prepareStatement(ProfileDBConstant.GET_ALL_PROFILE_CONFIGS); prepStmt.setInt(1, tenantId); prepStmt.setInt(2, tenantId); prepStmt.setInt(3, tenantId); prepStmt.setInt(4, tenantId); ResultSet rs = prepStmt.executeQuery(); while (rs.next()) { String claimUri = rs.getString(1); String profileName = rs.getString(2); short behavior = rs.getShort(3); String dialectUri = rs.getString(4); ProfileConfiguration profConfig = map.get(profileName); if (profConfig == null) { profConfig = new ProfileConfiguration(); map.put(profileName, profConfig); } profConfig.setDialectName(dialectUri); profConfig.setProfileName(profileName); if (behavior == UserCoreConstants.BEHAVIOUR_HIDDEN) { profConfig.addHiddenClaim(claimUri); } else if (behavior == UserCoreConstants.BEHAVIOUR_INHERITED) { profConfig.addInheritedClaim(claimUri); } else if (behavior == UserCoreConstants.BEHAVIOUR_OVERRIDDEN) { profConfig.addOverriddenClaim(claimUri); } else { assert (false); } } } catch (SQLException e) { String errorMessage = "Database Error - " + e.getMessage(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection, prepStmt); } return map; }
Example 11
Source File: AvaticaResultSetConversionsTest.java From calcite-avatica with Apache License 2.0 | 4 votes |
public short getShort(ResultSet r) throws SQLException { return r.getShort(label); }
Example 12
Source File: JdbcResolver.java From pxf with Apache License 2.0 | 4 votes |
/** * getFields() implementation * * @param row one row * @throws SQLException if the provided {@link OneRow} object is invalid */ @Override public List<OneField> getFields(OneRow row) throws SQLException { ResultSet result = (ResultSet) row.getData(); LinkedList<OneField> fields = new LinkedList<>(); for (ColumnDescriptor column : columns) { String colName = column.columnName(); Object value; OneField oneField = new OneField(); oneField.type = column.columnTypeCode(); fields.add(oneField); /* * Non-projected columns get null values */ if (!column.isProjected()) continue; switch (DataType.get(oneField.type)) { case INTEGER: value = result.getInt(colName); break; case FLOAT8: value = result.getDouble(colName); break; case REAL: value = result.getFloat(colName); break; case BIGINT: value = result.getLong(colName); break; case SMALLINT: value = result.getShort(colName); break; case BOOLEAN: value = result.getBoolean(colName); break; case BYTEA: value = result.getBytes(colName); break; case VARCHAR: case BPCHAR: case TEXT: case NUMERIC: value = result.getString(colName); break; case DATE: value = result.getDate(colName); break; case TIMESTAMP: value = result.getTimestamp(colName); break; default: throw new UnsupportedOperationException( String.format("Field type '%s' (column '%s') is not supported", DataType.get(oneField.type), column)); } oneField.val = result.wasNull() ? null : value; } return fields; }
Example 13
Source File: ColumnMetaData.java From calcite-avatica with Apache License 2.0 | 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 14
Source File: GroupsQueryImpl.java From ade with GNU General Public License v3.0 | 4 votes |
/** * Update the models table so if a deleted group name is being referenced, it is no longer * used as the default model. Also checks if one of the deleted groups is the UNASSIGNED group. * and if a new internal id has been given to the UNASSIGNED group. If so, we treat this as a * RENAMED group and need to update the database accordingly. * @param batchList a list of sql batch command strings to add to. * @param groupsToDelete list of groups to be deleted from the database. * @throws SQLException */ private void updateModelsTable(List<String> batchList, List<Group> groupsToDelete) throws SQLException{ if (!groupsToDelete.isEmpty()) { // Get the list of the models that are associated with a group. PreparedStatement modelListStatement = prepareStatement("SELECT MODEL_INTERNAL_ID, ANALYSIS_GROUP, IS_DEFAULT " + "FROM MODELS WHERE ANALYSIS_GROUP IS NOT NULL"); ResultSet modelsResult = modelListStatement.executeQuery(); // Lock the models table in exclusive mode. This may seem heavy handed, but // it's possible the a new model could be inserted after the "list" action // is performed here and as a result that model would reference a now // non-existent analysis group if (mySQL) batchList.add("LOCK TABLES " + MODELS_TABLE + " WRITE, " + GROUPS_TABLE + " WRITE, " + RULES_TABLE + " WRITE, " + SOURCES_TABLE + " WRITE, " + ANALYSIS_GROUPS_TIME_TABLE + " WRITE, " + MANAGED_SYSTEMS_TABLE + " WRITE"); else batchList.add("LOCK TABLE " + MODELS_TABLE + " IN EXCLUSIVE MODE"); // Iterate over the models to update analysis group names while (modelsResult.next()) { int groupId = modelsResult.getInt("ANALYSIS_GROUP"); short isDefault = modelsResult.getShort("IS_DEFAULT"); if (unassignedIsInGroups(groupsToDelete,groupId) && (unassignedGroupId != UNASSIGNED_ANALYSIS_GROUP_ID)){ batchList.add("UPDATE " + MODELS_TABLE + " SET ANALYSIS_GROUP=" + unassignedGroupId + " WHERE MODEL_INTERNAL_ID=" + modelsResult.getInt("MODEL_INTERNAL_ID")); } else if (isDefault == 1 && isInGroups(groupsToDelete,groupId)){ batchList.add("UPDATE " + MODELS_TABLE + " SET IS_DEFAULT=0 WHERE " + "MODEL_INTERNAL_ID=" + modelsResult.getInt("MODEL_INTERNAL_ID")); } } // Clean up modelsResult.close(); modelListStatement.close(); if (mySQL) this.execute("UNLOCK TABLES"); } }
Example 15
Source File: ImportFromDBManagerBase.java From ermaster-b with Apache License 2.0 | 4 votes |
private void setForeignKeys(ERTable target) throws SQLException { String tableName = target.getPhysicalName(); String schemaName = target.getTableViewProperties( this.dbSetting.getDbsystem()).getSchema(); ResultSet foreignKeySet = null; try { foreignKeySet = this.metaData.getImportedKeys(null, schemaName, tableName); List<ForeignKeyData> foreignKeyList = new ArrayList<ForeignKeyData>(); while (foreignKeySet.next()) { ForeignKeyData foreignKeyData = new ForeignKeyData(); foreignKeyData.name = foreignKeySet.getString("FK_NAME"); foreignKeyData.sourceTableName = foreignKeySet .getString("PKTABLE_NAME"); foreignKeyData.sourceSchemaName = foreignKeySet .getString("PKTABLE_SCHEM"); foreignKeyData.sourceColumnName = foreignKeySet .getString("PKCOLUMN_NAME"); foreignKeyData.targetSchemaName = foreignKeySet .getString("FKTABLE_SCHEM"); foreignKeyData.targetColumnName = foreignKeySet .getString("FKCOLUMN_NAME"); foreignKeyData.updateRule = foreignKeySet .getShort("UPDATE_RULE"); foreignKeyData.deleteRule = foreignKeySet .getShort("DELETE_RULE"); foreignKeyList.add(foreignKeyData); } if (foreignKeyList.isEmpty()) { return; } Map<String, List<ForeignKeyData>> sameNameForeignKeyDataMap = this .collectSameNameForeignKeyData(foreignKeyList); for (Map.Entry<String, List<ForeignKeyData>> entry : sameNameForeignKeyDataMap .entrySet()) { this.createRelation(target, entry.getValue()); } } catch (SQLException e) { // microsoft access does not support getImportedKeys } finally { this.close(foreignKeySet); } }
Example 16
Source File: PgBulkInsertPrimitivesTest.java From PgBulkInsert with MIT License | 4 votes |
@Test public void saveAll_Short_Test() throws SQLException { // This list will be inserted. List<SampleEntity> entities = new ArrayList<>(); // Create the Entity to insert: SampleEntity entity = new SampleEntity(); entity.col_short = 1; entities.add(entity); PgBulkInsert<SampleEntity> pgBulkInsert = new PgBulkInsert<>(new SampleEntityMapping()); pgBulkInsert.saveAll(PostgreSqlUtils.getPGConnection(connection), entities.stream()); ResultSet rs = getAll(); while (rs.next()) { short v = rs.getShort("col_smallint"); Assert.assertEquals(1, v); } }
Example 17
Source File: GemFireXDResolver.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
private OneField parseField(ResultSet rs, int i) throws Exception { // Indexing in rs starts at 1. final DataType type = this.columnTypeMapping[i]; switch (type) { case SMALLINT: return new OneField(DataType.SMALLINT.getOID(), rs.getShort(this.columnIndexMapping[i])); case INTEGER: return new OneField(DataType.INTEGER.getOID(), rs.getInt(this.columnIndexMapping[i])); case BIGINT: return new OneField(DataType.BIGINT.getOID(), rs.getLong(this.columnIndexMapping[i])); case REAL: return new OneField(DataType.REAL.getOID(), rs.getFloat(this.columnIndexMapping[i])); case FLOAT8: return new OneField(DataType.FLOAT8.getOID(), rs.getDouble(this.columnIndexMapping[i])); case VARCHAR: return new OneField(DataType.VARCHAR.getOID(), rs.getString(this.columnIndexMapping[i])); case BOOLEAN: return new OneField(DataType.BOOLEAN.getOID(), rs.getBoolean(this.columnIndexMapping[i])); case NUMERIC: return new OneField(DataType.NUMERIC.getOID(), rs.getBigDecimal(this.columnIndexMapping[i])); case TIMESTAMP: return new OneField(DataType.TIMESTAMP.getOID(), rs.getTimestamp(this.columnIndexMapping[i])); case DATE: return new OneField(DataType.DATE.getOID(), rs.getDate(this.columnIndexMapping[i])); case TIME: return new OneField(DataType.TIME.getOID(), rs.getTime(this.columnIndexMapping[i])); case CHAR: return new OneField(DataType.CHAR.getOID(), rs.getString(this.columnIndexMapping[i])); case BPCHAR: return new OneField(DataType.BPCHAR.getOID(), rs.getString(this.columnIndexMapping[i])); case BYTEA: return new OneField(DataType.BYTEA.getOID(), rs.getBytes(this.columnIndexMapping[i])); case TEXT: return new OneField(DataType.TEXT.getOID(), rs.getString(this.columnIndexMapping[i])); default: throw new Exception("Column type " + type + " is not supported."); } }
Example 18
Source File: QuarkMetaResultSet.java From quark with Apache License 2.0 | 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; } 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 19
Source File: JdbcUtils.java From flink with Apache License 2.0 | 4 votes |
public static Object getFieldFromResultSet(int index, int type, ResultSet set) throws SQLException { Object ret; switch (type) { case java.sql.Types.NULL: ret = null; break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: ret = set.getBoolean(index + 1); break; case java.sql.Types.CHAR: case java.sql.Types.NCHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: case java.sql.Types.LONGNVARCHAR: ret = set.getString(index + 1); break; case java.sql.Types.TINYINT: ret = set.getByte(index + 1); break; case java.sql.Types.SMALLINT: ret = set.getShort(index + 1); break; case java.sql.Types.INTEGER: ret = set.getInt(index + 1); break; case java.sql.Types.BIGINT: ret = set.getLong(index + 1); break; case java.sql.Types.REAL: ret = set.getFloat(index + 1); break; case java.sql.Types.FLOAT: case java.sql.Types.DOUBLE: ret = set.getDouble(index + 1); break; case java.sql.Types.DECIMAL: case java.sql.Types.NUMERIC: ret = set.getBigDecimal(index + 1); break; case java.sql.Types.DATE: ret = set.getDate(index + 1); break; case java.sql.Types.TIME: ret = set.getTime(index + 1); break; case java.sql.Types.TIMESTAMP: ret = set.getTimestamp(index + 1); break; case java.sql.Types.BINARY: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: ret = set.getBytes(index + 1); break; default: ret = set.getObject(index + 1); LOG.warn("Unmanaged sql type ({}) for column {}. Best effort approach to get its value: {}.", type, index + 1, ret); break; // case java.sql.Types.SQLXML // case java.sql.Types.ARRAY: // case java.sql.Types.JAVA_OBJECT: // case java.sql.Types.BLOB: // case java.sql.Types.CLOB: // case java.sql.Types.NCLOB: // case java.sql.Types.DATALINK: // case java.sql.Types.DISTINCT: // case java.sql.Types.OTHER: // case java.sql.Types.REF: // case java.sql.Types.ROWID: // case java.sql.Types.STRUC } if (set.wasNull()) { return null; } else { return ret; } }
Example 20
Source File: ResultSets.java From sqlhelper with GNU Lesser General Public License v3.0 | 4 votes |
/** * 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); }