Example usage for java.sql ResultSet next

List of usage examples for java.sql ResultSet next

Introduction

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

Prototype

boolean next() throws SQLException;

Source Link

Document

Moves the cursor forward one row from its current position.

Usage

From source file:dsd.dao.WorstCaseDAO.java

public static long GetMaxTimestamp(boolean traffic, boolean debris) {
    long timestamp = 0;
    try {/*  w  w w .  j a  v a2 s.  co m*/
        Connection con = DAOProvider.getDataSource().getConnection();
        try {
            String tableName = GetTableNameForDataType(traffic, debris);
            ResultSet results = DAOProvider.SelectTableSecure(tableName, " max(timestamp) ", "", "", con, null);
            while (results.next()) {
                timestamp = results.getTimestamp(1).getTime();
            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        con.close();
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    return timestamp;
}

From source file:ca.sqlpower.persistance.CatNap.java

public static void load(Connection con, String tableName, Object loadTo, String where)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException {
    BeanUtils.describe(loadTo);/*from  w w w.  java 2 s. co  m*/
    Statement stmt = null;
    StringBuffer sql = new StringBuffer();
    try {
        sql.append("SELECT * FROM " + tableName + " WHERE " + where);
        sql.append("\n");

        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql.toString());
        while (rs.next()) {
            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String beanPropertyName = underscoreToCamelCaps(metaData.getColumnName(i).toLowerCase());

                BeanUtils.setProperty(loadTo, beanPropertyName, rs.getObject(i));

            }
        }
    } catch (SQLException ex) {
        System.err.println("Catnap: Insert failed. Statement was:\n" + sql);
        throw ex;
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException ex) {
            System.err.println(
                    "Catnap: Couldn't close the statement.  Damn.  But at least you won a stack trace:");
            ex.printStackTrace();
        }
    }
}

From source file:com.bluepandora.therap.donatelife.adminpanel.JsonBuilder.java

public static JSONObject getDonatorListJson(ResultSet result) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject;/*from w w w . java2  s  . c  o  m*/
    try {
        while (result.next()) {
            jsonObject = new JSONObject();
            jsonObject.put(jsMobileNumber, result.getString(dbMobileNumber));
            jsonObject.put(jsFirstName, result.getString(dbFirstName));
            jsonObject.put(jsLastName, result.getString(dbLastName));
            jsonObject.put(jsGroupName, result.getString(dbGroupName));
            jsonObject.put(jsDistName, result.getString(dbDistName));
            jsonObject.put(jsGcmId, result.getString(dbGcmId));
            jsonArray.put(jsonObject);
        }
        jsonObject = new JSONObject();
        jsonObject.put(jsDonatorList, jsonArray);
        jsonObject.put(jsDONE, 1);
    } catch (SQLException error) {
        Debug.debugLog("DONATOR RESULT SET: ", error);
        jsonObject = new JSONObject();
        jsonObject.put(jsDONE, 0);
    }
    return jsonObject;
}

From source file:com.bluepandora.therap.donatelife.adminpanel.JsonBuilder.java

public static JSONObject getFeedBackJson(ResultSet result) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject;//  w w w  .ja  v a  2  s.c  o  m
    try {

        while (result.next()) {
            jsonObject = new JSONObject();
            jsonObject.put(jsIdUser, result.getString(dbIdUser));
            jsonObject.put(jsReqTime, result.getString(dbReqTime));
            jsonObject.put(jsSubject, result.getString(dbSubject));
            jsonObject.put(jsComment, result.getString(dbComment));
            jsonArray.put(jsonObject);
        }

        jsonObject = new JSONObject();
        jsonObject.put(jsfeedBackList, jsonArray);
        jsonObject.put(jsDONE, 1);
    } catch (SQLException error) {
        Debug.debugLog("FEEDBACK RESULT SET: ", error);
        jsonObject = new JSONObject();
        jsonObject.put(jsDONE, 0);
    }
    return jsonObject;
}

From source file:com.sql.EmailOutInvites.java

/**
 * Get a list of all of the email invites awaiting to be sent.
 * /*w w w . j av  a2  s.co m*/
 * @return List EmailOutInvitesModel
 */
public static List<EmailOutInvitesModel> getQueuedEmailInvites() {
    List<EmailOutInvitesModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM EmailOutInvites";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            EmailOutInvitesModel item = new EmailOutInvitesModel();
            item.setId(rs.getInt("id"));
            item.setSection(rs.getString("Section") == null ? "" : rs.getString("Section"));
            item.setToAddress(rs.getString("TOaddress") == null ? "" : rs.getString("TOaddress"));
            item.setCcAddress(rs.getString("CCaddress") == null ? "" : rs.getString("CCaddress"));
            item.setEmailBody(rs.getString("emailBody") == null ? "" : rs.getString("emailBody"));
            item.setCaseNumber(rs.getString("caseNumber") == null ? "" : rs.getString("caseNumber"));
            item.setHearingType(rs.getString("hearingType") == null ? "" : rs.getString("hearingType"));
            item.setHearingRoomAbv(
                    rs.getString("hearingRoomAbv") == null ? "" : rs.getString("hearingRoomAbv"));
            item.setHearingDescription(
                    rs.getString("hearingDescription") == null ? "" : rs.getString("hearingDescription"));
            item.setHearingStartTime(
                    CalendarCalculation.adjustTimeZoneOffset(rs.getTimestamp("hearingStartTime")));
            item.setHearingEndTime(CalendarCalculation.adjustTimeZoneOffset(rs.getTimestamp("hearingEndTime")));
            item.setEmailSubject(rs.getString("emailSubject") == null ? "" : rs.getString("emailSubject"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:org.usip.osp.graphs.GraphServer.java

public static Chart getChartByNameAndRound(String chart_id, String game_round, String sim_id,
        String values_table) {/*from  w  w w  .  j a  v  a2 s .c  om*/

    Chart cci = new Chart();

    String selectChartInfo = "SELECT * FROM `charts` where sf_id = '" //$NON-NLS-1$
            + chart_id + "'"; //$NON-NLS-1$

    try {
        Connection connection = MultiSchemaHibernateUtil.getConnection();
        Statement stmt = connection.createStatement();
        ResultSet rst = stmt.executeQuery(selectChartInfo);

        if (rst.next()) {
            String chart_type = rst.getString("type"); //$NON-NLS-1$
            String chart_title = rst.getString("title"); //$NON-NLS-1$
            String x_axis_title = rst.getString("x_axis_title"); //$NON-NLS-1$
            String y_axis_title = rst.getString("y_axis_title"); //$NON-NLS-1$

            //cci.height = rst.getInt("height");
            //cci.width = rst.getInt("width");

            String howToGetData = rst.getString("first_data_source"); //$NON-NLS-1$

            howToGetData = howToGetData.replace("[simulation_id]", sim_id); //$NON-NLS-1$
            howToGetData = howToGetData.replace("[sim_value_table_name]", values_table); //$NON-NLS-1$

            Statement stmt2 = connection.createStatement();
            ResultSet rst2 = stmt.executeQuery(howToGetData);

            JFreeChart chart = null;

            if (chart_type.equalsIgnoreCase("LineChart")) { //$NON-NLS-1$

                DefaultCategoryDataset cd = DataGatherer.getChartData(chart_type, game_round, howToGetData);

                chart = ChartFactory.createLineChart(chart_title, // chart
                        // title
                        x_axis_title, // domain axis label
                        y_axis_title, // range axis label
                        cd, // data
                        PlotOrientation.VERTICAL, // orientation
                        false, // include legend
                        true, // tooltips
                        false // urls
                );

            } else if (chart_type.equalsIgnoreCase("BarChart")) { //$NON-NLS-1$

                DefaultPieDataset dataset = DataGatherer.getPieData(chart_id, game_round, howToGetData);

                chart = ChartFactory.createPieChart(chart_title, dataset, true, // legend?
                        true, // tooltips?
                        false // URLs?
                );
            }

            cci.setThis_chart(chart);

        } // End of loop if found chart info

        connection.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return cci;
}

From source file:com.keybox.manage.db.ProfileDB.java

/**
 * method to do order by based on the sorted set object for profiles
 * @return list of profiles/* ww w .  ja v a 2 s.  com*/
 */
public static SortedSet getProfileSet(SortedSet sortedSet) {

    ArrayList<Profile> profileList = new ArrayList<>();

    String orderBy = "";
    if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
        orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
    }
    String sql = "select distinct p.* from  profiles p ";
    if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) {
        sql = sql + ", system_map m, system s where m.profile_id = p.id and m.system_id = s.id"
                + " and (lower(s.display_nm) like ? or lower(s.host) like ?)";
    } else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) {
        sql = sql + ", user_map m, users u where m.profile_id = p.id and m.user_id = u.id"
                + " and (lower(u.first_nm) like ? or lower(u.last_nm) like ?"
                + " or lower(u.email) like ? or lower(u.username) like ?)";
    }
    sql = sql + orderBy;

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(sql);
        if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) {
            stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%");
            stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%");
        } else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) {
            stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
            stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
            stmt.setString(3, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
            stmt.setString(4, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
        }
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            Profile profile = new Profile();
            profile.setId(rs.getLong("id"));
            profile.setNm(rs.getString("nm"));
            profile.setDesc(rs.getString("desc"));
            profileList.add(profile);

        }
        DBUtils.closeRs(rs);
        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    } finally {
        DBUtils.closeConn(con);
    }

    sortedSet.setItemList(profileList);
    return sortedSet;
}

From source file:com.sql.CaseType.java

/**
 * Gathers a list of active case types for finding the proper section based 
 * on the case number.//from   w w w.ja  v a 2s  .com
 * 
 * @return List CaseTypeModel
 */
public static List<CaseTypeModel> getCaseTypes() {
    List<CaseTypeModel> list = new ArrayList();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = DBConnection.connectToDB();
        String sql = "SELECT * FROM CaseType WHERE active = 1";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            CaseTypeModel item = new CaseTypeModel();
            item.setId(rs.getInt("id"));
            item.setActive(rs.getBoolean("active"));
            item.setSection(rs.getString("Section"));
            item.setCaseType(rs.getString("caseType"));
            item.setDescription(rs.getString("Description"));
            list.add(item);
        }
    } catch (SQLException ex) {
        ExceptionHandler.Handle(ex);
    } finally {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }
    return list;
}

From source file:Main.java

private static void outputResultSet(ResultSet rs) throws Exception {
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numberOfColumns = rsMetaData.getColumnCount();
    for (int i = 1; i < numberOfColumns + 1; i++) {
        String columnName = rsMetaData.getColumnName(i);
        System.out.print(columnName + "   ");

    }//www  .j av a2  s . co m
    while (rs.next()) {
        for (int i = 1; i < numberOfColumns + 1; i++) {
            System.out.print(rs.getString(i) + "   ");
        }
        System.out.println();
    }
}

From source file:com.l2jfree.gameserver.util.TableOptimizer.java

public static void optimize() {
    Connection con = null;/*from   www  . j ava2s  .  c o m*/
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        Statement st = con.createStatement();

        final ArrayList<String> tables = new ArrayList<String>();
        {
            ResultSet rs = st.executeQuery("SHOW FULL TABLES");
            while (rs.next()) {
                String tableType = rs.getString(2/*"Table_type"*/);

                if (tableType.equals("VIEW"))
                    continue;

                tables.add(rs.getString(1));
            }
            rs.close();
        }

        {
            ResultSet rs = st.executeQuery("CHECK TABLE " + StringUtils.join(tables, ","));
            while (rs.next()) {
                String table = rs.getString("Table");
                String msgType = rs.getString("Msg_type");
                String msgText = rs.getString("Msg_text");

                if (msgType.equals("status"))
                    if (msgText.equals("OK"))
                        continue;

                _log.warn("TableOptimizer: CHECK TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();

            _log.info("TableOptimizer: Database tables have been checked.");
        }

        {
            ResultSet rs = st.executeQuery("ANALYZE TABLE " + StringUtils.join(tables, ","));
            while (rs.next()) {
                String table = rs.getString("Table");
                String msgType = rs.getString("Msg_type");
                String msgText = rs.getString("Msg_text");

                if (msgType.equals("status"))
                    if (msgText.equals("OK") || msgText.equals("Table is already up to date"))
                        continue;

                _log.warn("TableOptimizer: ANALYZE TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();

            _log.info("TableOptimizer: Database tables have been analyzed.");
        }

        {
            ResultSet rs = st.executeQuery("OPTIMIZE TABLE " + StringUtils.join(tables, ","));
            while (rs.next()) {
                String table = rs.getString("Table");
                String msgType = rs.getString("Msg_type");
                String msgText = rs.getString("Msg_text");

                if (msgType.equals("status"))
                    if (msgText.equals("OK") || msgText.equals("Table is already up to date"))
                        continue;

                if (msgType.equals("note"))
                    if (msgText.equals("Table does not support optimize, doing recreate + analyze instead"))
                        continue;

                _log.warn("TableOptimizer: OPTIMIZE TABLE " + table + ": " + msgType + " -> " + msgText);
            }
            rs.close();

            _log.info("TableOptimizer: Database tables have been optimized.");
        }
        st.close();
    } catch (Exception e) {
        _log.warn("TableOptimizer: Cannot optimize database tables!", e);
    } finally {
        L2DatabaseFactory.close(con);
    }
}