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:it.webappcommon.lib.dao.AbstractBaseDAO.java

public T getById(int id) throws Exception {
    T returnValue = null;//from   www  .  ja v  a  2 s. c o  m

    PreparedStatement prpStmt = null;
    StringBuilder sqlQuery = null;
    ResultSet rs = null;

    try {

        sqlQuery = new StringBuilder();

        sqlQuery.append("SELECT * FROM ");
        sqlQuery.append(" " + getNomeTabella() + " ");
        sqlQuery.append("WHERE TRUE");
        // Verifico se e' specificato un filtro
        if (getCampoID() != null) {
            sqlQuery.append(" AND " + getCampoID() + " = " + String.valueOf(id));
        }
        // Verifico se e' specificato un campo cancellazione
        if (getCampoDataCancellazione() != null) {
            sqlQuery.append(" AND " + getCampoDataCancellazione() + " IS NULL");
        }

        String sqlString = sqlQuery.toString();
        logger.debug(sqlString);
        prpStmt = getConnection().prepareStatement(sqlString);
        logger.debug(prpStmt);
        rs = prpStmt.executeQuery();

        if (rs.first()) {
            returnValue = this.filler(rs);
        }

        // commit();
    } catch (Exception ex) {
        // rollback();
        logger.error(prpStmt, ex);
        throw ex;
    } finally {
        DAOUtils.close(getConnection(), prpStmt, rs, connApertaQui);
    }

    return returnValue;
}

From source file:beproject.MainGUI.java

void getTimeLineData(TimeSeriesCollection t) throws SQLException {
    Statement stmt = Initializer.inConn2.createStatement();
    ResultSet rs1 = stmt.executeQuery("select max(ts) from tweets");
    rs1.first();
    Timestamp ts1 = rs1.getTimestamp(1);
    for (String tmp : ScheduledMoviesList.getMovieNames()) {
        TimeSeries t1 = new TimeSeries(tmp, Hour.class);
        Timestamp ts = (Timestamp) ts1.clone();
        for (int i = 0; i < 6; i++) {
            Date d1 = new java.util.Date(ts.getTime());
            Date d2 = new java.util.Date(ts.getTime() + 3600000);
            ResultSet rs = stmt//from w  ww  .ja  va  2s.  c o m
                    .executeQuery("select count(*) from tweets where moviename='" + tmp + "' and ts between '"
                            + Regression.sdf.format(d1) + "' and '" + Regression.sdf.format(d2) + "'");
            rs.first();
            //if(!rs.first())
            //  t1.addOrUpdate(new Hour(d1), 0);
            //else
            t1.addOrUpdate(new Hour(d1), rs.getInt(1));
            ts.setTime(ts.getTime() - 3600000);
        }
        t.addSeries(t1);
    }

}

From source file:oscar.oscarRx.util.RxUtil.java

public static void setSpecialQuantityRepeat(RxPrescriptionData.Prescription rx) {

    try {/*from   ww w. j  av  a  2s .  c  o  m*/

        ResultSet rs;
        if (rx.getRegionalIdentifier() != null && rx.getRegionalIdentifier().length() > 1) {
            p("if1");
            p(rx.getRegionalIdentifier());
            //query the database to see if there is a rx with same din as this rx.
            // String sql = "SELECT * FROM drugs WHERE regional_identifier='" + rx.getRegionalIdentifier() + "' order by written_date desc"; //most recent is the first.
            String sql = "SELECT * FROM drugs WHERE regional_identifier='" + rx.getRegionalIdentifier()
                    + "' and BN='" + StringEscapeUtils.escapeSql(rx.getBrandName()) + "' AND demographic_no="
                    + rx.getDemographicNo() + " AND provider_no = '" + rx.getProviderNo()
                    + "' order by drugid desc"; //most recent is the first.
            MiscUtils.getLogger().debug("sql 1=" + sql);
            rs = DBHandler.GetSQL(sql);
            if (rs.first()) {//use the first result if there are multiple.
                setResultSpecialQuantityRepeat(rx, rs);
            } else {
                setDefaultSpecialQuantityRepeat(rx);
            }
        } else {
            p("else2");
            if (rx.getBrandName() != null && rx.getBrandName().length() > 1) {
                p("if2");
                //String sql2 = "SELECT * FROM drugs WHERE BN='" + StringEscapeUtils.escapeSql(rx.getBrandName()) + "' order by written_date desc"; //most recent is the first.
                String sql2 = "SELECT * FROM drugs WHERE BN='" + StringEscapeUtils.escapeSql(rx.getBrandName())
                        + "' AND demographic_no=" + rx.getDemographicNo() + " AND provider_no = '"
                        + rx.getProviderNo() + "' order by drugid desc"; //most recent is the first.
                MiscUtils.getLogger().debug("sql 2=" + sql2);
                //if none, query database to see if there is rx with same brandname.
                //if there are multiple, use latest.
                rs = DBHandler.GetSQL(sql2);
                if (rs.first()) {
                    setResultSpecialQuantityRepeat(rx, rs);
                } else {
                    //else, set to special to "", quantity to "30", repeat to "0".
                    setDefaultSpecialQuantityRepeat(rx);
                }
            } else {
                p("if3");
                if (rx.getCustomName() != null && rx.getCustomName().length() > 1) {
                    p("customName is not null");
                    //String sql3 = "SELECT * FROM drugs WHERE customName='" + StringEscapeUtils.escapeSql(rx.getCustomName()) + "' order by written_date desc"; //most recent is the first.
                    String sql3 = "SELECT * FROM drugs WHERE customName='"
                            + StringEscapeUtils.escapeSql(rx.getCustomName()) + "'  AND demographic_no="
                            + rx.getDemographicNo() + " AND provider_no = '" + rx.getProviderNo()
                            + "' order by drugid desc"; //most recent is the first.
                    MiscUtils.getLogger().debug("sql 3=" + sql3);
                    //if none, query database to see if there is rx with same customName.
                    //if there are multiple, use latest.
                    rs = DBHandler.GetSQL(sql3);
                    if (rs.first()) {
                        setResultSpecialQuantityRepeat(rx, rs);
                    } else {
                        setDefaultSpecialQuantityRepeat(rx);
                    }
                } else {
                    //else, set to special to "", quantity to "30", repeat to "0".
                    setDefaultSpecialQuantityRepeat(rx);
                }
            }
        }
    } catch (SQLException e) {
        logger.error("SQL Query ERROR", e);
    } finally {
        DbConnectionFilter.releaseThreadLocalDbConnection();
    }
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * Removes all the records from all the tables
 *//* w w w  . j  av a2  s  . c  om*/
public static void cleanAllTables(final Connection connection, SERVERTYPE currentServerType) {
    try {
        Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        ResultSet rs = stmt.executeQuery("show tables");
        if (rs.first()) {
            do {
                String tableName = rs.getString(1);
                //System.out.println("Deleting Records from "+tableName);
                deleteAllRecordsFromTable(connection, tableName, currentServerType);
            } while (rs.next());
        }
        rs.close();

        stmt.clearBatch();
        stmt.close();

    } catch (SQLException ex) {
        edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex);
        log.error(ex);
        ex.printStackTrace();
    }
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * Returns a count of the records query by SQL passed in.
 * @param sql the SQL with a 'count(?)' 
 * @return the number of records or zero
 *///  ww  w .j  a v a  2  s. c  om
public static int getNumRecords(final String sql, final Connection conn) {
    Statement cntStmt = null;
    try {
        int count = 0;

        if (conn != null) {
            cntStmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            if (cntStmt != null) {
                ResultSet rs = cntStmt.executeQuery(sql);
                if (rs.first()) {
                    count = rs.getInt(1);
                }
                rs.close();
            }
            cntStmt.close();
        }
        return count;

    } catch (SQLException ex) {
        edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex);
        log.error(ex);

    } finally {
        try {
            if (cntStmt != null) {
                cntStmt.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    return 0;
}

From source file:edu.ku.brc.specify.conversion.BasicSQLUtils.java

/**
 * Returns the number of records in a table
 * @param connection db connection/* w w w .java  2  s. com*/
 * @param tableName the name of the table
 * @return the number of records in a table
 */
public static int getNumRecords(final Connection connection, final String tableName) {
    try {
        Integer count = 0;
        Statement cntStmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = cntStmt.executeQuery("select count(*) from " + tableName);
        if (rs.first()) {
            count = rs.getInt(1);
            if (count == null) {
                return -1;
            }
        }
        rs.close();
        cntStmt.close();

        return count;

    } catch (SQLException ex) {
        log.error(ex);
        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BasicSQLUtils.class, ex);
    }
    return -1;
}

From source file:com.l2jfree.gameserver.handler.admincommands.AdminEditNpc.java

private int findOrderCustomTradeList(int itemID, long price, int tradeListID) {
    Connection con = null;/*w  w w .ja  v  a 2  s.  co m*/
    int order = 0;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement stmt = con.prepareStatement("SELECT * FROM custom_merchant_buylists WHERE `shop_id`='"
                + tradeListID + "' AND `item_id` ='" + itemID + "' AND `price` = '" + price + "'");
        ResultSet rs = stmt.executeQuery();
        rs.first();

        order = rs.getInt("order");

        stmt.close();
        rs.close();
    } catch (SQLException esql) {
        esql.printStackTrace();
    } finally {
        L2DatabaseFactory.close(con);
    }

    return order;
}

From source file:com.l2jfree.gameserver.handler.admincommands.AdminEditNpc.java

private int findOrderTradeList(int itemID, long price, int tradeListID) {
    Connection con = null;//from www .  j  a va 2s  .  c  o m
    int order = 0;
    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement stmt = con.prepareStatement(
                "SELECT * FROM merchant_buylists WHERE `shop_id` = ? AND `item_id` = ? AND `price` = ?");
        stmt.setInt(1, tradeListID);
        stmt.setInt(2, itemID);
        stmt.setLong(3, price);
        ResultSet rs = stmt.executeQuery();
        rs.first();

        order = rs.getInt("order");

        stmt.close();
        rs.close();
    } catch (SQLException esql) {
        esql.printStackTrace();
    } finally {
        L2DatabaseFactory.close(con);
    }

    return order;
}

From source file:database.DataLoader.java

private int getRowCount(ResultSet res) throws SQLException {
    int count = 0;
    while (res.next()) {
        count++;/*from  w w  w.  j  a v a  2 s. co  m*/
    }
    res.first();
    return count;
}

From source file:it.webappcommon.lib.dao.AbstractBaseDAO.java

public int getNum(F filtro) throws Exception {
    int res = 0;/*ww w. j ava  2 s  .  c o  m*/

    PreparedStatement prpStmt = null;
    StringBuilder sqlQuery = null;
    ResultSet rs = null;

    try {
        sqlQuery = new StringBuilder();
        sqlQuery.append("SELECT COUNT(*) as TOT FROM ");
        sqlQuery.append(" " + getNomeTabella() + " ");
        sqlQuery.append("WHERE ");
        if (filtro != null) {
            sqlQuery.append(filtro.getSQLWhere());
        } else {
            sqlQuery.append(QueryBuilder.ALWAYS_TRUE); // TODO: se il
            // filtro e' null
            // non
            // posso accodare il resto delle
            // conzioni di base se non faccio
            // questo.
        }
        if (getCampoDataCancellazione() != null && !filtro.isIncludeDeleted()) {
            sqlQuery.append(" AND " + getCampoDataCancellazione() + " IS NULL");
        }

        String sqlString = sqlQuery.toString();
        logger.debug(sqlString);
        prpStmt = getConnection().prepareStatement(sqlString);
        logger.debug(prpStmt);
        rs = prpStmt.executeQuery();

        if (rs.first()) {
            res = rs.getInt("TOT");
        }

    } catch (Exception ex) {
        // rollback();
        logger.error(prpStmt, ex);
        throw ex;
    } finally {
        DAOUtils.close(getConnection(), prpStmt, rs, connApertaQui);
    }

    return res;
}