Example usage for java.sql ResultSet getObject

List of usage examples for java.sql ResultSet getObject

Introduction

In this page you can find the example usage for java.sql ResultSet getObject.

Prototype

Object getObject(String columnLabel) throws SQLException;

Source Link

Document

Gets the value of the designated column in the current row of this ResultSet object as an Object in the Java programming language.

Usage

From source file:com.surfs.storage.common.datasource.jdbc.JdbcDao.java

@Override
public Object insert(String poolName, String sql, Object... params) throws Exception {
    Connection conn = null;//from   www .  j  a  v a  2s. co m
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = getConnection(poolName);
        ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        for (int i = 0; i < params.length; i++) {
            if (params[i] instanceof String)
                ps.setString(i + 1, (String) params[i]);
            else if (params[i] instanceof Integer)
                ps.setInt(i + 1, (Integer) params[i]);
            else if (params[i] instanceof Long)
                ps.setLong(i + 1, (Long) params[i]);
            else if (params[i] instanceof Timestamp)
                ps.setTimestamp(i + 1, (Timestamp) params[i]);
        }
        ps.execute();
        rs = ps.getGeneratedKeys();
        if (rs.next())
            return rs.getObject(1);
        return null;
    } catch (Exception e) {
        throw e;
    } finally {
        JdbcUtils.closeResultset(rs);
        JdbcUtils.closeStatement(ps);
        JdbcUtils.closeConnect(conn);
    }
}

From source file:com.geodetix.geo.dao.PostGisGeometryDAOImpl.java

/**
 * PostGIS implementation of the  //from w ww .j  ava  2s .co m
 * {@link com.geodetix.geo.interfaces.GeometryLocalHome#findByPolygon(org.postgis.Polygon)}
 * method
 * 
 * @return a collection of bean's primary key beeing found.
 * @param polygon the {@link org.postgis.Polygon} to search in.
 * @throws javax.ejb.FinderException launched if an error occours during the search operation.
 */
public java.util.Collection findByPolygon(org.postgis.Polygon polygon) throws javax.ejb.FinderException {

    PreparedStatement pstm = null;
    Connection con = null;
    ResultSet result = null;

    try {

        con = this.dataSource.getConnection();

        pstm = con.prepareStatement(PostGisGeometryDAO.FIND_BY_POLYGON_STATEMENT);

        pstm.setObject(1, new PGgeometry(polygon));

        result = pstm.executeQuery();

        Vector keys = new Vector();

        while (result.next()) {
            keys.addElement(result.getObject("id"));
        }

        return keys;

    } catch (SQLException se) {
        throw new EJBException(se);

    } finally {
        try {
            if (result != null) {
                result.close();
            }
        } catch (Exception e) {
        }

        try {
            if (pstm != null) {
                pstm.close();
            }
        } catch (Exception e) {
        }

        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
        }
    }
}

From source file:Database.Handler.java

@SuppressWarnings("unchecked")
private List<T> mapRersultSetToObject(ResultSet rs, Class outputClass) {
    List<T> outputList = null;
    try {/*from  www .  j a v  a 2 s .co m*/
        if (rs != null) {
            if (outputClass.isAnnotationPresent(Entity.class)) {
                ResultSetMetaData rsmd = rs.getMetaData();
                Field[] fields = outputClass.getDeclaredFields();
                while (rs.next()) {
                    T bean = (T) outputClass.newInstance();
                    //System.out.println("rsmd = "+rsmd.getColumnCount());
                    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                        String columnName = rsmd.getColumnName(i);
                        Object columnValue = rs.getObject(i);
                        for (Field field : fields) {
                            if (field.isAnnotationPresent(Column.class)) {
                                Column column = field.getAnnotation(Column.class);
                                if (column.name().equalsIgnoreCase(columnName) && columnValue != null) {
                                    //System.out.println(field.getName() + "=====>" + columnValue);
                                    BeanUtils.setProperty(bean, field.getName(), columnValue);
                                    break;
                                }
                            }
                        }
                    }
                    if (outputList == null) {
                        outputList = new ArrayList<T>();
                    }
                    outputList.add(bean);
                }
            } else {
                // throw some error
                System.out.println("output class is not annotationPresented");
            }
        } else {
            return null;
        }
    } catch (SQLException ex) {
        Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return outputList;
}

From source file:ResultSetIterator.java

/**
 * Convert a <code>ResultSet</code> column into an object.  Simple 
 * implementations could just call <code>rs.getObject(index)</code> while
 * more complex implementations could perform type manipulation to match 
 * the column's type to the bean property type.
 * //  w  w w .  ja  va2s.co m
 * <p>
 * This implementation calls the appropriate <code>ResultSet</code> getter 
 * method for the given property type to perform the type conversion.  If 
 * the property type doesn't match one of the supported 
 * <code>ResultSet</code> types, <code>getObject</code> is called.
 * </p>
 * 
 * @param rs The <code>ResultSet</code> currently being processed.  It is
 * positioned on a valid row before being passed into this method.
 * 
 * @param index The current column index being processed.
 * 
 * @param propType The bean property type that this column needs to be
 * converted into.
 * 
 * @throws SQLException if a database access error occurs
 * 
 * @return The object from the <code>ResultSet</code> at the given column
 * index after optional type processing or <code>null</code> if the column
 * value was SQL NULL.
 */
protected Object processColumn(ResultSet rs, int index, Class propType) throws SQLException {

    if (!propType.isPrimitive() && rs.getObject(index) == null) {
        return null;
    }

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

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

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

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

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

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

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

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

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

    } else {
        return rs.getObject(index);
    }

}

From source file:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

@Override
public EbMSMessageStatus getMessageStatus(String messageId) throws DAOException {
    try {//from   w  w  w.j a va 2s .c om
        return EbMSMessageStatus.get(simpleJdbcTemplate.queryForObject(
                "select status" + " from ebms_message" + " where message_id = ?",
                new ParameterizedRowMapper<Integer>() {
                    @Override
                    public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
                        return rs.getObject("status") == null ? null : rs.getInt("status");
                    }
                }, messageId));
    } catch (EmptyResultDataAccessException e) {
        return EbMSMessageStatus.NOT_RECOGNIZED;
    } catch (DataAccessException e) {
        throw new DAOException(e);
    }
}

From source file:org.opennms.ng.services.poller.Poller.java

private int scheduleMatchingServices(String criteria) {
    String sql = "SELECT ifServices.nodeId AS nodeId, node.nodeLabel AS nodeLabel, ifServices.ipAddr AS ipAddr, "
            + "ifServices.serviceId AS serviceId, service.serviceName AS serviceName, ifServices.status as status, "
            + "outages.svcLostEventId AS svcLostEventId, events.eventUei AS svcLostEventUei, "
            + "outages.ifLostService AS ifLostService, outages.ifRegainedService AS ifRegainedService "
            + "FROM ifServices " + "JOIN node ON ifServices.nodeId = node.nodeId "
            + "JOIN service ON ifServices.serviceId = service.serviceId " + "LEFT OUTER JOIN outages ON "
            + "ifServices.nodeId = outages.nodeId AND " + "ifServices.ipAddr = outages.ipAddr AND "
            + "ifServices.serviceId = outages.serviceId AND " + "ifRegainedService IS NULL "
            + "LEFT OUTER JOIN events ON outages.svcLostEventId = events.eventid "
            + "WHERE ifServices.status in ('A','N')" + (criteria == null ? "" : " AND " + criteria);

    final AtomicInteger count = new AtomicInteger(0);

    Querier querier = new Querier(m_dataSource, sql) {
        @Override/*from  w  w  w  .  j  a  v a  2 s . c  om*/
        public void processRow(ResultSet rs) throws SQLException {
            if (scheduleService(rs.getInt("nodeId"), rs.getString("nodeLabel"), rs.getString("ipAddr"),
                    rs.getString("serviceName"), "A".equals(rs.getString("status")),
                    (Number) rs.getObject("svcLostEventId"), rs.getTimestamp("ifLostService"),
                    rs.getString("svcLostEventUei"))) {
                count.incrementAndGet();
            }
        }
    };
    querier.execute();

    return count.get();
}

From source file:computer_store.GUI.java

/**
 * Takes a JTable and a ResultSet as parameters and populates the JTable with the supplied ResultSet
 * @param table/*ww  w. j a va2  s .  c  o m*/
 * @param rs 
 */
private void fillTable(javax.swing.JTable table, java.sql.ResultSet rs) {
    try {

        //To remove previously added rows
        while (table.getRowCount() > 0) {
            ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(0);
        }
        int columns = rs.getMetaData().getColumnCount();
        Object[] ids = new Object[columns];
        while (rs.next()) {
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++) {
                row[i - 1] = rs.getObject(i);
            }
            ((javax.swing.table.DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
        }
        for (int i = 1; i <= columns; i++) {
            ids[i - 1] = rs.getMetaData().getColumnName(i);
        }
        ((javax.swing.table.DefaultTableModel) table.getModel()).setColumnIdentifiers(ids);
        rs.close();
    } catch (Exception e) {
        System.out.print(e);
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String postGIS_example3() {
    //http://postgis.net/docs/manual-1.4/ch05.html
    //apt-get install libpostgis-java
    //Nepovedlo se zprovoznit
    Connection conn;/*  www .  jav  a 2  s  . co m*/

    try {
        /* 
         * Load the JDBC driver and establish a connection. 
         */
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://localhost:5432/user";
        conn = DriverManager.getConnection(url, "user", "user");

        //((org.postgresql.PGConnection)conn).addDataType("point", "org.postgis.PGpoint");
        /* 
         * Create a statement and execute a select query. 
         */
        Statement s = conn.createStatement();
        ResultSet r = s.executeQuery("SELECT ST_AsText(geom) as geom, gid FROM archsites");
        while (r.next()) {
            PGpoint geom = (PGpoint) r.getObject(1);
            int gid = r.getInt(2);
            System.out.println("Row " + gid + ":");
            System.out.println(geom.toString());
        }
        s.close();
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "Done";
}

From source file:com.quangphuong.crawler.dbutil.DBWrapper.java

public Object getEntity(Class<?> entity, Object... id) {
    String sql = selectAll.concat(entity.getSimpleName());
    sql = sql.concat(whereClause);// w  w  w.  java2 s  . c  om
    Connection con = DBHandler.openConnection();
    Object result = null;
    try {
        Statement statement = con.createStatement();
        Field[] attributes = entity.getDeclaredFields();
        int count = 0;
        for (int i = 0; i < attributes.length; i++) {
            Field attribute = attributes[i];
            if (attribute.isAnnotationPresent(Id.class)) {
                if (i == 0) {
                    sql = sql.concat(attribute.getName() + "=" + "\'" + id[count] + "\'");
                } else {
                    sql = sql.concat(" AND " + attribute.getName() + "=" + "\'" + id[count] + "\'");
                }
                count++;
            }
        }
        System.out.println(sql);
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            List<Object> listFields = new ArrayList();
            List<Class<?>> listFieldTypes = new ArrayList();
            for (Field attribute : attributes) {
                if (!attribute.isAnnotationPresent(Ignore.class)) {
                    Object obj = resultSet.getObject(attribute.getName());
                    listFields.add(obj);
                    listFieldTypes.add(obj.getClass());
                }
            }
            result = entity.getConstructor((Class<?>[]) listFieldTypes.toArray(new Class[0]))
                    .newInstance(listFields.toArray());
        }
    } catch (Exception ex) {
        Logger.getLogger(DBWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:flex.messaging.io.ASRecordSet.java

public void populate(ResultSet rs) throws IOException {

    try {/*from w ww.  ja  va2  s  .  co  m*/
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        String[] columnNames = new String[columnCount];

        int rowIndex = 0;
        List<List<Object>> initialData = new ArrayList<List<Object>>();
        while (rs.next()) {
            rowIndex++;
            List<Object> row = new ArrayList<Object>();
            for (int column = 0; column < columnCount; column++) {
                if (rowIndex == 1) {
                    columnNames[column] = rsmd.getColumnName(column + 1);
                }
                row.add(rs.getObject(column + 1));
            }
            if (rowIndex == 1) {
                setColumnNames(columnNames);
            }
            rows.add(row);
            if (rowIndex <= initialRowCount) {
                initialData.add(row);
            }
        }
        setTotalCount(rowIndex);
        setInitialData(initialData);
        setColumnNames(columnNames);
    } catch (SQLException e) {
        throw new IOException(e.getMessage());
    }

}