java.sql.ResultSet#getShort ( )源码实例Demo

下面列出了java.sql.ResultSet#getShort ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: netbeans   文件: MySQLProcedure.java
/**
 * 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);
}
 
源代码2 项目: gemfirexd-oss   文件: ConcurrentConnTest.java
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();
}
 
源代码3 项目: geoportal-server-harvester   文件: JdbcBroker.java
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;
}
 
@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;
}
 
源代码5 项目: ade   文件: GroupsQueryImpl.java
/**
 * 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);            
}
 
源代码6 项目: XPagesExtensionLibrary   文件: JdbcDebugUtil.java
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$
}
 
源代码7 项目: cacheonix-core   文件: TableMetadata.java
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();
	}
}
 
源代码8 项目: gemfirexd-oss   文件: SQLSmallint.java
/** 
 * @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;

	}
}
 
源代码9 项目: micro-integrator   文件: ProfileConfigDAO.java
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;
}
 
源代码10 项目: sqlhelper   文件: ResultSets.java
/**
 * 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);
}
 
源代码11 项目: flink   文件: JdbcUtils.java
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;
	}
}
 
源代码12 项目: quark   文件: QuarkMetaResultSet.java
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);
  }
}
 
源代码13 项目: gemfirexd-oss   文件: GemFireXDResolver.java
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.");
  }
}
 
源代码14 项目: PgBulkInsert   文件: PgBulkInsertPrimitivesTest.java
@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);
    }
}
 
源代码15 项目: ermaster-b   文件: ImportFromDBManagerBase.java
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);
	}
}
 
源代码16 项目: ade   文件: GroupsQueryImpl.java
/**
       * 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");
          }            
      }
 
源代码17 项目: calcite-avatica   文件: ColumnMetaData.java
/** 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);
  }
}
 
源代码18 项目: pxf   文件: JdbcResolver.java
/**
 * 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;
}
 
public short getShort(ResultSet r) throws SQLException {
  return r.getShort(label);
}
 
源代码20 项目: gemfirexd-oss   文件: TPCETradeResult.java
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();
}