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

The following are Jave code examples for showing how to use getObject() 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: scorekeeperfrontend   File: MergeServer.java   View Source Code Vote up 6 votes
public MergeServer(ResultSet rs) throws SQLException
{
    serverid    = (UUID)rs.getObject("serverid");
    hostname    = rs.getString("hostname");
    address     = rs.getString("address");
    lastcheck   = rs.getTimestamp("lastcheck", Database.utc);
    nextcheck   = rs.getTimestamp("nextcheck", Database.utc);
    waittime    = rs.getInt("waittime");
    ctimeout    = rs.getInt("ctimeout");
    cfailures   = rs.getInt("cfailures");
    String hs   = rs.getString("hoststate");
    switch (hs) {
        case "A": hoststate = HostState.ACTIVE; break;
        case "1": hoststate = HostState.ONESHOT; break;
        case "I": hoststate = HostState.INACTIVE; break;
        default:  hoststate = HostState.UNKNOWN; break;
    }
    seriesstate = new HashMap<String, JSONObject>();
    try {
        JSONObject mergestate = (JSONObject)new JSONParser().parse(rs.getString("mergestate"));
        for (Object o : mergestate.keySet()) {
            seriesstate.put((String)o, (JSONObject)mergestate.get(o));
        }
    } catch (ParseException e) {
    }
}
 
Example 2
Project: parabuild-ci   File: Testdb.java   View Source Code Vote up 6 votes
public static void dump(ResultSet rs) throws SQLException {

        // the order of the rows in a cursor
        // are implementation dependent unless you use the SQL ORDER statement
        ResultSetMetaData meta   = rs.getMetaData();
        int               colmax = meta.getColumnCount();
        int               i;
        Object            o = null;

        // the result set is a cursor into the data.  You can only
        // point to one row at a time
        // assume we are pointing to BEFORE the first row
        // rs.next() points to next row and returns true
        // or false if there is no next row, which breaks the loop
        for (; rs.next(); ) {
            for (i = 0; i < colmax; ++i) {
                o = rs.getObject(i + 1);    // Is SQL the first column is indexed

                // with 1 not 0
                System.out.print(o.toString() + " ");
            }

            System.out.println(" ");
        }
    }
 
Example 3
Project: eXperDB-DB2PG   File: DatabaseUtil.java   View Source Code Vote up 6 votes
public static Object PreparedStmtSetValue(int columnType, ResultSet rs, int index) throws SQLException, IOException{
	StringBuffer sb = new StringBuffer();
	switch(columnType){
	case 2005:  //CLOB
		Clob clob = rs.getClob(index);
		
		if (clob == null){
			return null;
		}
		
		Reader reader = clob.getCharacterStream();
		char[] buffer = new char[(int)clob.length()];
		while(reader.read(buffer) != -1){
			sb.append(buffer);				
		}
		return sb.toString();
	case 2004:  //BLOB			
		Blob blob = rs.getBlob(index);
		
		if (blob == null){
			return null;
		}
		
		InputStream in = blob.getBinaryStream();
		byte[] Bytebuffer = new byte[(int)blob.length()];
		in.read(Bytebuffer);
		return Bytebuffer;
	case -2:
		return rs.getBytes(index);
	default:
		return rs.getObject(index);
	}	
}
 
Example 4
Project: scorekeeperfrontend   File: Driver.java   View Source Code Vote up 5 votes
public Driver(ResultSet rs) throws SQLException
{
    super(rs);
    driverid   = (UUID)rs.getObject("driverid");
    firstname  = rs.getString("firstname");
    lastname   = rs.getString("lastname");
    email      = rs.getString("email");
    username   = rs.getString("username");
    password   = rs.getString("password");
    membership = rs.getString("membership");
    optoutmail = rs.getBoolean("optoutmail");
}
 
Example 5
Project: lams   File: EnumType.java   View Source Code Vote up 5 votes
private void resolveEnumValueMapper(ResultSet rs, String name) {
	if ( enumValueMapper == null ) {
		try {
			resolveEnumValueMapper( rs.getMetaData().getColumnType( rs.findColumn( name ) ) );
		}
		catch (Exception e) {
			// because some drivers do not implement this
			LOG.debugf(
					"JDBC driver threw exception calling java.sql.ResultSetMetaData.getColumnType; " +
							"using fallback determination [%s] : %s",
					enumClass.getName(),
					e.getMessage()
			);
			// peek at the result value to guess type (this is legacy behavior)
			try {
				Object value = rs.getObject( name );
				if ( Number.class.isInstance( value ) ) {
					treatAsOrdinal();
				}
				else {
					treatAsNamed();
				}
			}
			catch (SQLException ignore) {
				treatAsOrdinal();
			}
		}
	}
}
 
Example 6
Project: adept   File: SingleHandler.java   View Source Code Vote up 5 votes
/**
 * 将'ResultSet'结果集的第一行、第一列的单个数据转换为'单个Object对象'的方法.
 * @param rs ResultSet实例
 * @return Object对象
 */
@Override
public Object transform(ResultSet rs) {
    if (rs == null) {
        return null;
    }

    // 遍历Resultset,返回第一行、第一列的单个数据.
    try {
        return rs.next() ? rs.getObject(1) : null;
    } catch (Exception e) {
        throw new ResultsTransformException("将'ResultSet'结果集转换为'map的List集合'出错!", e);
    }
}
 
Example 7
Project: bdf2   File: DbJdbcUtils.java   View Source Code Vote up 5 votes
public static Map<Integer, Object> getTable(Connection conn, String tableSchema, String tableName) throws Exception {
	Map<Integer, Object> table = new HashMap<Integer, Object>();
	DatabaseMetaData databaseMetaData = conn.getMetaData();
	if (tableSchema == null) {
		tableSchema = getDefaultTableSchema(conn);
	}
	String[] t = { "TABLE" };
	ResultSet rs = null;
	try {
		rs = databaseMetaData.getTables(null, tableSchema, tableName.toUpperCase(), t);
		while (rs.next()) {
			int i = 1;
			while (i <= 10) {
				Object obj = null;
				try {
					obj = rs.getObject(i);
				} catch (SQLException e) {
					break;
				}
				table.put(i, obj);
				i++;
			}
		}
		return table;
	} finally {
		DbJdbcUtils.closeResultSet(rs);
	}
}
 
Example 8
Project: morpheus-core   File: DbSourceOptions.java   View Source Code Vote up 5 votes
/**
 * Constructor
 */
@SuppressWarnings("unchecked")
public DbSourceOptions() {
    this.rowCapacity = 1000;
    this.excludeColumnSet = new HashSet<>();
    this.extractorMap = new HashMap<>();
    this.rowKeyFunction = (ResultSet rs) -> {
        try {
            return (R)rs.getObject(1);
        } catch (SQLException ex) {
            throw new RuntimeException("Failed to read row key from SQL ResultSet", ex);
        }
    };
}
 
Example 9
Project: bdf2   File: DbJdbcUtils.java   View Source Code Vote up 5 votes
public static List<Map<Integer, Object>> getTableColumn(Connection conn, String tableSchema, String tableName) throws Exception {
	List<Map<Integer, Object>> columnInfos = new ArrayList<Map<Integer, Object>>();
	Map<Integer, Object> columnInfo;
	DatabaseMetaData databaseMetaData = conn.getMetaData();
	if (tableSchema == null) {
		tableSchema = getDefaultTableSchema(conn);
	}
	ResultSet rs = null;
	try {
		rs = databaseMetaData.getColumns(null, tableSchema, tableName.toUpperCase(), "%");
		while (rs.next()) {
			columnInfo = new HashMap<Integer, Object>();
			int i = 1;
			while (i <= 23) {
				Object obj = null;
				try {
					obj = rs.getObject(i);
				} catch (SQLException e) {
					break;
				}
				columnInfo.put(i, obj);
				i++;
			}
			columnInfos.add(columnInfo);
		}
		return columnInfos;
	} finally {
		DbJdbcUtils.closeResultSet(rs);
	}
}
 
Example 10
Project: graphium   File: WayGraphViewRowMapper.java   View Source Code Vote up 5 votes
@Override
public IWayGraphView mapRow(ResultSet rs, int rowNum) throws SQLException {
	byte[] coveredAreaBytes = rs.getBytes("covered_area");
	return new WayGraphView(rs.getString("viewname"), 
							new WayGraph(rs.getLong("graph_id"), rs.getString("graph_name")), 
							rs.getString("dbviewname"),
							rs.getBoolean("waysegments_included"),
							(coveredAreaBytes == null ? null : (Polygon) bp.parse(coveredAreaBytes)), 
							rs.getInt("segments_count"), 
							rs.getInt("connections_count"),
							(Map<String, String>) rs.getObject("tags"));
}
 
Example 11
Project: scorekeeperfrontend   File: Payment.java   View Source Code Vote up 5 votes
public Payment(ResultSet rs) throws SQLException
{
    payid    = (UUID)rs.getObject("payid");
    eventid  = (UUID)rs.getObject("eventid");
    carid    = (UUID)rs.getObject("carid");
    refid    = rs.getString("refid");
    txtype   = rs.getString("txtype");
    txid     = rs.getString("txid");
    txtime   = rs.getTimestamp("txtime", Database.utc);
    itemname = rs.getString("itemname");
    amount   = rs.getDouble("amount");
}
 
Example 12
Project: x7   File: DaoImpl.java   View Source Code Vote up 4 votes
@SuppressWarnings("rawtypes")
@Override
public long getMaxId(Object conditionObj) {

	long id = 0;

	Class clz = conditionObj.getClass();

	String sql = MapperFactory.getSql(clz, Mapper.PAGINATION);

	Parsed parsed = Parser.get(clz);

	Map<String, Object> queryMap = BeanUtilX.getQueryMap(parsed, conditionObj);
	sql = SqlUtil.concat(parsed, sql, queryMap);

	sql = sql.replace(X.PAGINATION, "max(id) maxId");

	Connection conn = null;
	PreparedStatement pstmt = null;
	try {
		conn = getConnection(true);
		conn.setAutoCommit(true);
		pstmt = conn.prepareStatement(sql);

		int i = 1;

		for (Object o : queryMap.values()) {
			pstmt.setObject(i++, o);
		}

		ResultSet rs = pstmt.executeQuery();

		if (rs.next()) {
			Object obj = rs.getObject("maxId");
			if (obj != null) {
				id = Long.valueOf(obj.toString());
			}
		}

	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		close(pstmt);
		close(conn);
	}

	return id;
}
 
Example 13
Project: x7   File: AsyncDaoImpl.java   View Source Code Vote up 4 votes
@Override
public <T> List<T> listSync(Class<T> clz) {

	filterTryToCreate(clz);

	List<T> list = new ArrayList<T>();

	String sql = MapperFactory.getSql(clz, Mapper.LOAD);
	List<BeanElement> eles = MapperFactory.getElementList(clz);

	Connection conn = null;
	PreparedStatement pstmt = null;
	BeanElement tempEle = null;
	try {
		conn = getConnection();
		conn.setAutoCommit(true);
		pstmt = conn.prepareStatement(sql);

		ResultSet rs = pstmt.executeQuery();

		if (rs != null) {
			while (rs.next()) {
				T obj = clz.newInstance();
				list.add(obj);
				for (BeanElement ele : eles) {
					Method method = ele.setMethod;
					// try {
					// method = obj.getClass().getDeclaredMethod(ele.setter,
					// ele.clz);
					// } catch (NoSuchMethodException e) {
					// method =
					// obj.getClass().getSuperclass().getDeclaredMethod(ele.setter,
					// ele.clz);
					// }
					if (ele.clz.getSimpleName().toLowerCase().equals("double")) {
						Object v = rs.getObject(ele.property);
						if (v != null) {
							method.invoke(obj, Double.valueOf(String.valueOf(v)));
						}
					} else {
						tempEle = ele;
						method.invoke(obj, rs.getObject(ele.property));
					}
				}
			}
		}

	} catch (Exception e) {
		if (tempEle != null) {
			System.out
					.println("Exception occured by class = " + clz.getName() + ", property = " + tempEle.property);
		}
		e.printStackTrace();
	} finally {
		close(pstmt);
		close(conn);
	}

	return list;
}
 
Example 14
Project: open-rmbt   File: OpenTestSearchResource.java   View Source Code Vote up 4 votes
/**
 * Map a ResultSet to the provided JSONArray,
 * return the uid from the last row
 *
 * @param rs
 * @param additionalFields
 * @param ret
 * @return
 * @throws SQLException
 * @throws JSONException
 */
public long mapToJson(ResultSet rs, Set<String> additionalFields, JSONArray ret) throws SQLException, JSONException {
    long lastUID = 0;
    while (rs.next())
    {
        final JSONObject jsonItem = new JSONObject();
        final HashMap<String, Object> item = new HashMap<>();

        for (int i=0;i<openDataFieldsSummary.length;i++) {
            final Object obj = rs.getObject(openDataFieldsSummary[i]);
            if (obj==null) {
                jsonItem.put(openDataFieldsSummary[i], JSONObject.NULL);
            } else if (openDataNumberFields.contains(openDataFieldsSummary[i])) {
                final String tmp = obj.toString().trim();
                if (tmp.isEmpty())
                    jsonItem.put(openDataFieldsSummary[i], JSONObject.NULL);
                else
                    jsonItem.put(openDataFieldsSummary[i], JSONObject.stringToValue(tmp));
            } else {
                jsonItem.put(openDataFieldsSummary[i], obj.toString());
            }

        }

        // add additional fields if requested by user
        if (additionalFields != null) {
            if (additionalFields.contains("download_classification")) {
                jsonItem.put("download_classification", Classification.classify(Classification.THRESHOLD_DOWNLOAD,rs.getLong("download_kbit"), 4));
            }
            if (additionalFields.contains("upload_classification")) {
                jsonItem.put("upload_classification", Classification.classify(Classification.THRESHOLD_UPLOAD,rs.getLong("upload_kbit"), 4));
            }
            if (additionalFields.contains("ping_classification")) {
                jsonItem.put("ping_classification", Classification.classify(Classification.THRESHOLD_PING,rs.getLong("ping_ms") * 1000000, 4));
            }
        }
        ret.put(jsonItem);
        lastUID = rs.getLong("cursor");
    }

    return lastUID;
}
 
Example 15
Project: YuiHatano   File: ShadowSQLiteDirectCursorDriver.java   View Source Code Vote up 4 votes
public Cursor query(ShadowSQLiteDatabase.CursorFactory factory, String[] selectionArgs) {
//        ShadowSQLiteQuery query  = new ShadowSQLiteQuery(mDatabase, mSql, selectionArgs, mCancellationSignal);
        try {
            String querySql = KbSqlParser.bindArgs(mSql, selectionArgs);

            mDatabase.debug(querySql);

            Connection connection = mDatabase.getConnection();
            Statement  statement  = connection.createStatement();

            ResultSet         rs          = statement.executeQuery(querySql);
            ResultSetMetaData metaData    = rs.getMetaData();
            int               columnCount = metaData.getColumnCount();
            List<String>      columns     = new ArrayList<>();

            // column name数组, colum从1开始
            for (int i = 1; i < columnCount + 1; i++) {
                String name = metaData.getColumnName(i);

                columns.add(name);
            }

            // 结果集合
            List<List<Object>> datas = new ArrayList<>();

            while (rs.next()) {
                List<Object> data = new ArrayList<>();

                // ResultSet colum从1开始
                for (int i = 1; i < columnCount + 1; i++) {
                    Object value = rs.getObject(i);

                    data.add(value);
                }

                datas.add(data);
            }

            rs.close();
            statement.close();

            ShadowCursor shadowCursor = new ShadowCursor(columns, datas);

            return shadowCursor;
        } catch (RuntimeException ex) {
            throw ex;
        } catch (java.sql.SQLException e) {
            throw new android.database.SQLException(e.getMessage());
        }

//        mQuery = query;
    }
 
Example 16
Project: ramus   File: PersistentWrapper.java   View Source Code Vote up 4 votes
public void setDatabaseField(Object persistent, PersistentField field,
                             ResultSet rs) throws SQLException {

    if (rs.getObject(field.getDatabaseName()) == null) {
        setField(persistent, field.getName(), null);
        return;
    }

    switch (field.getType()) {
        case PersistentField.ATTRIBUTE:
        case PersistentField.ID:
        case PersistentField.QUALIFIER:
        case PersistentField.ELEMENT:
        case PersistentField.LONG:
            setField(persistent, field.getName(),
                    rs.getLong(field.getDatabaseName()));
            break;
        case PersistentField.DATE:
            Timestamp timestamp = rs.getTimestamp(field.getDatabaseName());
            setField(persistent, field.getName(), timestamp);
            break;
        case PersistentField.DOUBLE:
            setField(persistent, field.getName(),
                    rs.getDouble(field.getDatabaseName()));
            break;
        case PersistentField.TEXT:
            setField(persistent, field.getName(),
                    rs.getString(field.getDatabaseName()));
            break;
        case PersistentField.BINARY:
            setField(persistent, field.getName(),
                    rs.getBytes(field.getDatabaseName()));
            break;
        case PersistentField.INTEGER:
            setField(persistent, field.getName(),
                    rs.getInt(field.getDatabaseName()));
            break;
        case PersistentField.VALUE_BRANCH_ID:
            setField(persistent, field.getName(),
                    rs.getLong(field.getDatabaseName()));
            break;

        default:
            throw new RuntimeException("Unknow field type to set.");
    }

}
 
Example 17
Project: ralasafe   File: ResultSetReader.java   View Source Code Vote up 4 votes
public Object reader(ResultSet rs, String columnName)
		throws SQLException {
	return rs.getObject(columnName);
}
 
Example 18
Project: spring-boot-starter-dao   File: GlobalEnumTypeHandler.java   View Source Code Vote up 4 votes
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
	Object s = rs.getObject(columnIndex);
	return this.findObject(s);
}
 
Example 19
Project: jetfuel   File: Database.java   View Source Code Vote up 2 votes
/**
 * Reads the identity column from a set of generated keys;
 * 
 * @param generated_keys
 * @param identity
 * @return
 * @throws SQLException
 */
public Object readIdentity(ResultSet generated_keys, Column identity) throws SQLException {
	return generated_keys.next()
			? generated_keys.getObject(1)
			: null;
}
 
Example 20
Project: otter-G   File: SqlUtils.java   View Source Code Vote up 2 votes
/**
 * Retrieve a JDBC column value from a ResultSet, using the most appropriate
 * value type. The returned value should be a detached value object, not
 * having any ties to the active ResultSet: in particular, it should not be
 * a Blob or Clob object but rather a byte array respectively String
 * representation.
 * <p>
 * Uses the <code>getObject(index)</code> method, but includes additional
 * "hacks" to get around Oracle 10g returning a non-standard object for its
 * TIMESTAMP datatype and a <code>java.sql.Date</code> for DATE columns
 * leaving out the time portion: These columns will explicitly be extracted
 * as standard <code>java.sql.Timestamp</code> object.
 * 
 * @param rs is the ResultSet holding the data
 * @param index is the column index
 * @return the value object
 * @throws SQLException if thrown by the JDBC API
 * @see java.sql.Blob
 * @see java.sql.Clob
 * @see java.sql.Timestamp
 */
private static String getResultSetValue(ResultSet rs, int index) throws SQLException {
    Object obj = rs.getObject(index);
    return (obj == null) ? null : convertUtilsBean.convert(obj);
}