Example usage for java.sql ResultSet first

List of usage examples for java.sql ResultSet first

Introduction

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

Prototype

boolean first() throws SQLException;

Source Link

Document

Moves the cursor to the first row in this ResultSet object.

Usage

From source file:org.cyrusbuilt.guncabinet.dao.DbEngine.java

/**
 * Gets the specified caliber./*  ww w. j  a va2s . c  o  m*/
 * @param id The ID of the caliber to retrieve.
 * @return If successful, a {@link org.cyrusbuilt.guncabinet.dao.entities.ChamberCaliberEntity}
 * matching the specified ID; Otherwise, null.
 * @throws ObjectDisposedException This instance has been disposed.
 * @throws SQLException A database access error occurred.
 * @throws DbDriverNotFoundException The MySQL database driver was not found.
 */
public ChamberCaliberEntity getCaliber(Integer id)
        throws ObjectDisposedException, SQLException, DbDriverNotFoundException {
    if (_isDisposed) {
        throw new ObjectDisposedException(this);
    }

    if (id <= 0) {
        return null;
    }

    ChamberCaliberEntity caliber = null;
    String query = "select * from " + this._dbName + "." + DbUtils.getTableName(Tables.ChamberCaliber)
            + " where Id='" + id.toString() + "'";
    ResultSet rs = this._stmt.executeQuery(query);
    if (rs.first()) {
        caliber = new ChamberCaliberEntity(rs.getInt("Id"), rs.getString("Name"));
        caliber.setNotes(rs.getString("Notes"));
        caliber.setNATO(rs.getBoolean("IsNATO"));
    }
    rs.close();
    return caliber;
}

From source file:org.sakaiproject.evalgroup.providers.SimpleEvalGroupProviderImpl.java

/**
 * @param groupId/*from  w  w  w.  j a v a 2 s . c  o  m*/
 * @return
 */
protected EvalGroup makeEvalGroupObject(String groupId) {
    Connection conn;
    ResultSet result;
    String title = "";
    try {
        conn = dataSource.getConnection();
        Statement statement = conn.createStatement();
        result = statement.executeQuery("Select * from GRP_PROVIDER_groups where id = " + groupId + ";");
        result.first();
        title = result.getString("title");
        conn.close();
    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
    return new EvalGroup(groupId, title, EvalConstants.GROUP_TYPE_PROVIDED);
}

From source file:org.esupportail.dining.web.feed.DiningData.java

public List<Restaurant> getFavoriteList(User user) {
    List<Restaurant> favorites = new ArrayList<Restaurant>();

    try {//from   w  w  w  . ja  va2 s.  co m
        ResultSet favList = this.dc.executeQuery(
                "SELECT RESTAURANTID FROM FAVORITERESTAURANT WHERE USERNAME='" + user.getLogin() + "';");

        if (favList.next()) {
            for (Restaurant r : this.feed.getFeed().getRestaurants()) {

                do {
                    if (r.getId() == favList.getInt("RESTAURANTID")) {
                        favorites.add(r);
                    }
                } while (favList.next());

                favList.first();
            }
        }

    } catch (SQLException e) {
        // Nothing to do here.
    } catch (NullPointerException e2) {
        // nop
    }

    return favorites;
}

From source file:com.norconex.collector.http.db.impl.derby.DerbyCrawlURLDatabase.java

@Override
public Iterator<CrawlURL> getCacheIterator() {
    try {/*  www.  ja  v a 2s  . c  o  m*/
        final Connection conn = datasource.getConnection();
        final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        final ResultSet rs = stmt.executeQuery(
                "SELECT url, depth, smLastMod, smChangeFreq, smPriority " + "FROM " + TABLE_CACHE);
        if (rs == null || !rs.first()) {
            return null;
        }
        rs.beforeFirst();
        return new CrawlURLIterator(rs, conn, stmt);
    } catch (SQLException e) {
        throw new CrawlURLDatabaseException("Problem getting database cache iterator.", e);
    }
}

From source file:MstrJadwal.Entry.java

private void ListPengajar() {
    try {/*from   w  w  w.j av a2  s .  com*/
        _Cnn = null;
        _Cnn = getCnn.getConnection();
        String sql = "" + "   SELECT id_guru,nama_guru " + "   FROM guru";
        Statement stat = _Cnn.createStatement();
        ResultSet res = stat.executeQuery(sql);
        cmb_nama_pengajar.removeAllItems();
        int i = 0;
        while (res.next()) {
            cmb_nama_pengajar.addItem(res.getString(2));
            i++;
        }
        res.first();
        KeyPengajar = new String[i + 1];
        for (Integer x = 0; x < i; x++) {
            KeyPengajar[x] = res.getString(1);
            res.next();
        }
    } catch (Exception ex) {
    }
}

From source file:netflow.DatabaseProxy.java

private boolean aggregationAlreadyStored(AggregationRecord record) throws SQLException {
    String query = getQuery("aggregation.record.exists");
    PreparedStatement ps = con.prepareStatement(query);
    ps.setInt(1, record.getClientId());//from  www.j  a  v  a2  s. c  o m
    ps.setDate(2, record.getDate());
    return doWithStatement(ps, new ResultSetProcessor<Boolean>() {
        @Override
        public Boolean process(ResultSet rs) throws SQLException {
            return rs.first();
        }
    });
}

From source file:com.redoute.datamap.dao.impl.PictureDAO.java

@Override
public Integer getNumberOfPicturePerCrtiteria(String searchTerm, String inds) {
    Integer result = 0;/*from   ww w  .j av a2  s .c om*/
    StringBuilder query = new StringBuilder();
    StringBuilder gSearch = new StringBuilder();
    String searchSQL = "";

    query.append("SELECT count(*) FROM picture");

    gSearch.append(" where (`id` like '%");
    gSearch.append(searchTerm);
    gSearch.append("%'");
    gSearch.append(" or `page` like '%");
    gSearch.append(searchTerm);
    gSearch.append("%'");
    gSearch.append(" or `application` like '%");
    gSearch.append(searchTerm);
    gSearch.append("%'");
    gSearch.append(" or `picture` like '%");
    gSearch.append(searchTerm);
    gSearch.append("%')");

    if (!searchTerm.equals("") && !inds.equals("")) {
        searchSQL = gSearch.toString() + " and " + inds;
    } else if (!inds.equals("")) {
        searchSQL = " where " + inds;
    } else if (!searchTerm.equals("")) {
        searchSQL = gSearch.toString();
    }

    query.append(searchSQL);

    Connection connection = this.databaseSpring.connect();
    try {
        PreparedStatement preStat = connection.prepareStatement(query.toString());
        try {
            ResultSet resultSet = preStat.executeQuery();
            try {

                if (resultSet.first()) {
                    result = resultSet.getInt(1);
                }

            } catch (SQLException exception) {
                Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
            } finally {
                resultSet.close();
            }

        } catch (SQLException exception) {
            Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
        } finally {
            preStat.close();
        }

    } catch (SQLException exception) {
        Logger.log(PictureDAO.class.getName(), Level.ERROR, exception.toString());
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            Logger.log(PictureDAO.class.getName(), Level.ERROR, e.toString());
        }
    }
    return result;

}

From source file:no.polaric.aprsdb.MyDBSession.java

/**
  * Get trail poiint for a given station and a given time. 
  */// ww  w  .  j  a  va2s.c o m
public Trail.Item getTrailPoint(String src, java.util.Date t) throws java.sql.SQLException {
    _log.debug("MyDbSession", "getTrailPoint: " + src + ", " + df.format(t));
    /* Left outer join with AprsPacket to get path where available */
    PreparedStatement stmt = getCon().prepareStatement(
            " SELECT pr.time, position, speed, course, path, ipath, nopkt FROM \"PosReport\" AS pr"
                    + " LEFT JOIN \"AprsPacket\" AS ap ON pr.src = ap.src AND pr.rtime = ap.time "
                    + " WHERE pr.src=? AND pr.time > ? AND pr.time < ?",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    stmt.setString(1, src);
    stmt.setTimestamp(2, date2ts(t, -1200));
    stmt.setTimestamp(3, date2ts(t, +1200));
    ResultSet rs = stmt.executeQuery();
    if (rs.first()) {
        String p = "";
        if (rs.getBoolean("nopkt"))
            p = "(ext)";
        else {
            String path = rs.getString("path");
            String ipath = rs.getString("ipath");
            if (path == null)
                p = "?";
            else {
                p = path;
                if (ipath != null && ipath.length() > 1)
                    p = p + (p.length() > 1 ? "," : "") + ipath;
            }
        }

        return new Trail.Item(rs.getTimestamp("time"), getRef(rs, "position"), rs.getInt("speed"),
                rs.getInt("course"), p);
    } else
        return null;
}

From source file:net.starschema.clouddb.jdbc.list.TreeBuilder.java

/**
 * Makes a JDBC call to get the possible prefixes of the specified table, if it finds
 * out that this query has already been run, uses the stored results instead
 *  //from w w w.ja  va  2  s. co  m
 * @param tableName - the Tables name which prefixes we want to know
 * @return - The prefixes of the Table
 */
@SuppressWarnings("rawtypes")
List<String> getPossiblePrefixes(String colName) {
    // we make jdbc calls to get columns
    this.logger.debug("making a jdbc call to get the Prefixes");
    List<String> Columns = new ArrayList<String>();
    try {
        // Try to get result from container first
        this.logger.debug("Try to get result from container first");
        Class[] args = new Class[4];
        args[0] = String.class;
        args[1] = String.class;
        args[2] = String.class;
        args[3] = String.class;
        Method method = null;
        try {
            this.logger.debug("getting the method: getcolumns");
            method = this.connection.getMetaData().getClass().getMethod("getColumns", args);
        } catch (SecurityException e) {
            // Should not occur
            this.logger.warn("failed to get the method getColumns " + e);
        } catch (NoSuchMethodException e) {
            // Should not occur
            this.logger.warn("failed to get the method getColumns " + e);
        }

        List<Parameter> params = new ArrayList<Parameter>();
        params.add(new Parameter(this.connection.getCatalog()));
        params.add(new Parameter("%"));
        params.add(new Parameter("%"));
        params.add(new Parameter(colName));
        ResultSet res = this.callContainer.getresult(method, params);
        if (res == null) {
            res = this.connection.getMetaData().getColumns(this.connection.getCatalog(), "%", "%", colName);
            this.callContainer.AddCall(res, method, params);
        }
        res.first();
        // Iterating through the results
        while (!res.isAfterLast()) {
            Columns.add(res.getString(2) + "." + res.getString(3));
            logger.debug("found prefix:" + res.getString(2) + "." + res.getString(3));
            res.next();
        }
    } catch (SQLException e) {
        // should not happen
        this.logger.warn("failed to get prefixes for the column: " + colName, e);
    }
    return Columns;
}

From source file:org.codesearch.commons.database.DBAccessImpl.java

/**
 * {@inheritDoc}/*from  w w  w  .j  ava  2  s. c o  m*/
 */
@Override
public synchronized int ensureThatRecordExists(String filePath, String repository)
        throws DatabaseAccessException {
    int fileId = getFileIdForFileName(filePath, repository);
    Connection conn = null;
    PreparedStatement statement = null;
    try {
        if (fileId == -1) {
            conn = dataSource.getConnection();
            // In case no record for this data exists
            statement = conn.prepareStatement(STMT_CREATE_FILE_RECORD, Statement.RETURN_GENERATED_KEYS);
            statement.setString(1, filePath);
            statement.setString(2, repository);
            statement.execute();
            ResultSet generatedKeys = statement.getGeneratedKeys();
            generatedKeys.first();
            fileId = generatedKeys.getInt(1);
        }
    } catch (SQLException ex) {
        throw new DatabaseAccessException("SQLException while trying to access the database\n" + ex);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
            }
        }
    }
    return fileId;
}