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:ua.aits.sdolyna.model.ArticleModel.java

public ArticleModel getArticleByIDAndLan(String id, String lan) throws SQLException {
    ResultSet result = DB.getResultSet("SELECT * FROM `sdolyna_content` WHERE `article_id` = " + id + ";");
    result.first();
    ArticleModel article = new ArticleModel();
    article.setArticle_id(result.getInt("article_id"));
    article.setArticle_title_ru(//  w w  w. j  a va  2  s . com
            result.getString("article_title_" + lan.toLowerCase()).replaceAll("\"", """));
    article.setArticle_title_en(result.getString("article_title_en").replaceAll("\"", """));
    article.setArticle_text_ru(result.getString("article_text_" + lan.toLowerCase()));
    article.setArticle_text_en(result.getString("article_text_en"));
    article.setArticle_category(result.getInt("article_category"));
    article.setArticle_date(result.getString("article_date"));
    article.setArticle_date_end(result.getString("article_date_end"));
    String langs = "";
    if (article.article_title_ru == "" || article.article_title_ru == null) {
        article.setArticle_title_ru("");
    }
    if (article.article_text_ru == "" || article.article_text_ru == null) {
        article.setArticle_text_ru("");
    }
    if (!"".equals(article.article_title_ru)) {
        langs += "RU,";
    }
    if (!"".equals(article.article_title_en)) {
        langs += "EN,";
    }
    if (langs != "") {
        article.setArticle_lang(langs.substring(0, langs.length() - 1));
    }
    article.setArticle_images(this.fillImages(article.article_id.toString()));

    DB.closeCon();
    return article;
}

From source file:com.theminequest.MineQuest.SQLExecutor.java

/**
 * Get a certain column from a ResultSet
 * @param rs ResultSet//from  w w w.ja v a  2 s  .c  om
 * @param columnname Column Name
 * @return list of <b>Strings</b> containing the contents of the column.
 * @throws SQLException If the ResultSet cannot be queried.
 */
public List<String> getColumn(ResultSet rs, String columnname) throws SQLException {
    if (rs == null)
        throw new IllegalArgumentException("ResultSet cannot be null!");
    List<String> toreturn = new ArrayList<String>();
    try {
        if (!rs.first())
            return toreturn;
        do {
            toreturn.add(rs.getString(columnname));
        } while (rs.next());
        return toreturn;
    } catch (SQLException e) {
        MineQuest.log(Level.SEVERE, "[SQL] SQL exception on ResultSet: " + e);
        throw e;
    }
}

From source file:giaodien.tongquan.TongQuan.java

public void showdata() {
    try {/*from w w w. j a  v  a2  s  .c o m*/

        PreparedStatement tongcachoadon = con
                .prepareStatement("select sum(TONGTIEN) as total from hoadonbanhang");
        ResultSet rstongcachoadon = tongcachoadon.executeQuery();
        rstongcachoadon.first();
        int sum = rstongcachoadon.getInt("total");
        System.out.println(sum);
        tfDoanhSo.setText("" + sum + "  VND ");

        PreparedStatement demhoadon = con.prepareStatement("select count(MAHOADONBANHANG) from hoadonbanhang");
        ResultSet rsdemhoadon = demhoadon.executeQuery();
        rsdemhoadon.first();
        int count = rsdemhoadon.getInt("count(MAHOADONBANHANG)");
        System.out.println(count);
        tfHoaDon.setText("" + count);

        PreparedStatement sovoihomqua = con.prepareStatement(
                "SELECT TONGTIEN FROM shop.hoadonbanhang WHERE THOIGIAN >= '2017-05-25 00:00:00' AND THOIGIAN <= '2017-05-25 23:59:59'");
        ResultSet rssovoihomqua = sovoihomqua.executeQuery();
        rstongcachoadon.first();
        int sum1 = rssovoihomqua.getInt("total");
        System.out.println(sum);
        //tfDoanhSo.setText(""+sum);

    } catch (Exception exc) {
        System.out.println(exc.getMessage());
    }

}

From source file:ua.aits.oblenergo_site.model.ArticleModel.java

public String deleteArticle(String id) throws SQLException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, IOException {
    ResultSet result = DB.getResultSet(
            "SELECT obl_articles.article_id, obl_articles.article_category FROM obl_articles WHERE obl_articles.article_id = "
                    + id + ";");
    result.first();
    DB.runQuery("UPDATE `obl_articles` SET `obl_articles.article_is_delete`= 1 WHERE obl_articles.article_id = "
            + id + ";");
    String category = result.getString("article_category");
    DB.closeCon();//from w  ww. j av  a  2s .  co  m
    return category;
}

From source file:org.cerberus.servlet.zzpublic.ResultCI.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());

    /**/*w  ww  .java2 s  .  c  o m*/
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(ILogEventService.class);
    logEventService.createPublicCalls("/ResultCI", "CALL", "ResultCIV0 called : " + request.getRequestURL(),
            request);

    String tag = policy.sanitize(request.getParameter("tag"));

    String helpMessage = "\nThis servlet is used to profide a global OK or KO based on the number and status of the execution done on a specific tag.\n"
            + "The number of executions are ponderated by parameters by priority from CI_OK_prio1 to CI_OK_prio4.\n"
            + "Formula used is the following :\n"
            + "Nb Exe Prio 1 testcases * CI_OK_prio1 + Nb Exe Prio 2 testcases * CI_OK_prio2 +\n"
            + "  Nb Exe Prio 3 testcases * CI_OK_prio3 + Nb Exe Prio 4 testcases * CI_OK_prio4\n\n"
            + "If not executions are found, the result is KO.\n"
            + "With at least 1 execution, if result is < 1 then global servlet result is OK. If not, it is KO.\n"
            + "All execution needs to have a status equal to KO, FA, NA or PE.\n\n" + "Parameter list :\n"
            + "- tag [mandatory] : Execution Tag to filter the test cases execution. [" + tag + "]\n";

    DatabaseSpring database = appContext.getBean(DatabaseSpring.class);

    Connection connection = database.connect();
    try {

        boolean error = false;

        // Checking the parameter validity. Tag is a mandatory parameter
        if (StringUtils.isBlank(tag)) {
            out.println("Error - Parameter tag is mandatory.");
            error = true;
        }

        if (!error) {

            PreparedStatement prepStmt = connection.prepareStatement("SELECT count(*) AS NBKOP1 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '1' " + "AND tag = ?");

            int nbkop1 = 0;
            try {
                prepStmt.setString(1, tag);
                ResultSet rs_resultp1 = prepStmt.executeQuery();
                try {
                    if (rs_resultp1.first()) {
                        nbkop1 = Integer.valueOf(rs_resultp1.getString("NBKOP1"));
                    }
                } finally {
                    rs_resultp1.close();
                }
            } finally {
                prepStmt.close();
            }

            PreparedStatement prepStmt2 = connection.prepareStatement("SELECT count(*) AS NBKOP2 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '2' " + "AND tag = ?");
            int nbkop2 = 0;
            try {
                prepStmt2.setString(1, tag);
                ResultSet rs_resultp2 = prepStmt2.executeQuery();
                try {
                    if (rs_resultp2.first()) {
                        nbkop2 = Integer.valueOf(rs_resultp2.getString("NBKOP2"));
                    }
                } finally {
                    rs_resultp2.close();
                }
            } finally {
                prepStmt2.close();
            }

            PreparedStatement prepStmt3 = connection.prepareStatement("SELECT count(*) AS NBKOP3 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '3' " + "AND tag = ?");
            int nbkop3 = 0;
            try {
                prepStmt3.setString(1, tag);
                ResultSet rs_resultp3 = prepStmt3.executeQuery();
                try {
                    if (rs_resultp3.first()) {
                        nbkop3 = Integer.valueOf(rs_resultp3.getString("NBKOP3"));
                    }
                } finally {
                    rs_resultp3.close();
                }
            } finally {
                prepStmt3.close();
            }

            PreparedStatement prepStmt4 = connection.prepareStatement("SELECT count(*) AS NBKOP4 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '4' " + "AND tag = ?");
            int nbkop4 = 0;
            try {
                prepStmt4.setString(1, tag);
                ResultSet rs_resultp4 = prepStmt4.executeQuery();
                try {
                    if (rs_resultp4.first()) {
                        nbkop4 = Integer.valueOf(rs_resultp4.getString("NBKOP4"));
                    }
                } finally {
                    rs_resultp4.close();
                }
            } finally {
                prepStmt4.close();
            }

            IParameterService parameterService = appContext.getBean(IParameterService.class);

            float pond1 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio1", "").getValue());
            float pond2 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio2", "").getValue());
            float pond3 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio3", "").getValue());
            float pond4 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio4", "").getValue());

            String result;
            float resultCal = (nbkop1 * pond1) + (nbkop2 * pond2) + (nbkop3 * pond3) + (nbkop4 * pond4);
            if (resultCal < 1) {
                result = "OK";
            } else {
                result = "KO";
            }
            out.print(result);

            // Log the result with calculation detail.
            logEventService.createPublicCalls("/ResultCI", "CALLRESULT",
                    "ResultCI calculated with result [" + result + "] : " + nbkop1 + "*" + pond1 + " + "
                            + nbkop2 + "*" + pond2 + " + " + nbkop3 + "*" + pond3 + " + " + nbkop4 + "*" + pond4
                            + " = " + resultCal,
                    request);

        } else {
            // In case of errors, we display the help message.
            out.println(helpMessage);
        }

    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        out.close();
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            MyLogger.log(ResultCI.class.getName(), org.apache.log4j.Level.WARN, e.toString());
        }
    }

}

From source file:org.cerberus.servlet.publi.ResultCI.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    ApplicationContext appContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());

    /**//from ww  w .java2s  .c  om
     * Adding Log entry.
     */
    ILogEventService logEventService = appContext.getBean(LogEventService.class);
    logEventService.insertLogEventPublicCalls("/ResultCI", "CALL",
            "ResultCIV0 called : " + request.getRequestURL(), request);

    String tag = policy.sanitize(request.getParameter("tag"));

    String helpMessage = "\nThis servlet is used to profide a global OK or KO based on the number and status of the execution done on a specific tag.\n"
            + "The number of executions are ponderated by parameters by priority from CI_OK_prio1 to CI_OK_prio4.\n"
            + "Formula used is the following :\n"
            + "Nb Exe Prio 1 testcases * CI_OK_prio1 + Nb Exe Prio 2 testcases * CI_OK_prio2 +\n"
            + "  Nb Exe Prio 3 testcases * CI_OK_prio3 + Nb Exe Prio 4 testcases * CI_OK_prio4\n\n"
            + "If not executions are found, the result is KO.\n"
            + "With at least 1 execution, if result is < 1 then global servlet result is OK. If not, it is KO.\n"
            + "All execution needs to have a status equal to KO, FA, NA or PE.\n\n" + "Parameter list :\n"
            + "- tag [mandatory] : Execution Tag to filter the test cases execution. [" + tag + "]\n";

    DatabaseSpring database = appContext.getBean(DatabaseSpring.class);

    Connection connection = database.connect();
    try {

        boolean error = false;

        // Checking the parameter validity. Tag is a mandatory parameter
        if (StringUtils.isBlank(tag)) {
            out.println("Error - Parameter tag is mandatory.");
            error = true;
        }

        if (!error) {

            PreparedStatement prepStmt = connection.prepareStatement("SELECT count(*) AS NBKOP1 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '1' " + "AND tag = ?");

            int nbkop1 = 0;
            try {
                prepStmt.setString(1, tag);
                ResultSet rs_resultp1 = prepStmt.executeQuery();
                try {
                    if (rs_resultp1.first()) {
                        nbkop1 = Integer.valueOf(rs_resultp1.getString("NBKOP1"));
                    }
                } finally {
                    rs_resultp1.close();
                }
            } finally {
                prepStmt.close();
            }

            PreparedStatement prepStmt2 = connection.prepareStatement("SELECT count(*) AS NBKOP2 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '2' " + "AND tag = ?");
            int nbkop2 = 0;
            try {
                prepStmt2.setString(1, tag);
                ResultSet rs_resultp2 = prepStmt2.executeQuery();
                try {
                    if (rs_resultp2.first()) {
                        nbkop2 = Integer.valueOf(rs_resultp2.getString("NBKOP2"));
                    }
                } finally {
                    rs_resultp2.close();
                }
            } finally {
                prepStmt2.close();
            }

            PreparedStatement prepStmt3 = connection.prepareStatement("SELECT count(*) AS NBKOP3 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '3' " + "AND tag = ?");
            int nbkop3 = 0;
            try {
                prepStmt3.setString(1, tag);
                ResultSet rs_resultp3 = prepStmt3.executeQuery();
                try {
                    if (rs_resultp3.first()) {
                        nbkop3 = Integer.valueOf(rs_resultp3.getString("NBKOP3"));
                    }
                } finally {
                    rs_resultp3.close();
                }
            } finally {
                prepStmt3.close();
            }

            PreparedStatement prepStmt4 = connection.prepareStatement("SELECT count(*) AS NBKOP4 "
                    + "FROM testcaseexecution t " + "JOIN " + "(SELECT Test,TestCase, Priority FROM testcase)b "
                    + "ON b.test= t.test AND b.testcase=t.testcase "
                    + "WHERE controlStatus not in ('OK') AND priority = '4' " + "AND tag = ?");
            int nbkop4 = 0;
            try {
                prepStmt4.setString(1, tag);
                ResultSet rs_resultp4 = prepStmt4.executeQuery();
                try {
                    if (rs_resultp4.first()) {
                        nbkop4 = Integer.valueOf(rs_resultp4.getString("NBKOP4"));
                    }
                } finally {
                    rs_resultp4.close();
                }
            } finally {
                prepStmt4.close();
            }

            IParameterService parameterService = appContext.getBean(ParameterService.class);

            float pond1 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio1", "").getValue());
            float pond2 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio2", "").getValue());
            float pond3 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio3", "").getValue());
            float pond4 = Float.valueOf(parameterService.findParameterByKey("CI_OK_prio4", "").getValue());

            String result;
            float resultCal = (nbkop1 * pond1) + (nbkop2 * pond2) + (nbkop3 * pond3) + (nbkop4 * pond4);
            if ((resultCal < 1) && (nbkop1 + nbkop2 + nbkop3 + nbkop4 > 0)) {
                result = "OK";
            } else {
                result = "KO";
            }
            out.print(result);

            // Log the result with calculation detail.
            logEventService.insertLogEventPublicCalls("/ResultCI", "CALLRESULT",
                    "ResultCI calculated with result [" + result + "] : " + nbkop1 + "*" + pond1 + " + "
                            + nbkop2 + "*" + pond2 + " + " + nbkop3 + "*" + pond3 + " + " + nbkop4 + "*" + pond4
                            + " = " + resultCal,
                    request);

        } else {
            // In case of errors, we display the help message.
            out.println(helpMessage);
        }

    } catch (Exception e) {
        out.println(e.getMessage());
    } finally {
        out.close();
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            MyLogger.log(ResultCI.class.getName(), org.apache.log4j.Level.WARN, e.toString());
        }
    }

}

From source file:com.google.enterprise.connector.salesforce.storetype.DBStore.java

public DocListEntry getDocsImmediatelyAfter(String checkpoint) {
    DatabaseMetaData dbm = null;/* w  w  w  .  ja  v a2  s  .com*/
    Connection connection = null;

    try {

        connection = ds.getConnection();
        connection.setAutoCommit(true);

        dbm = connection.getMetaData();
        //get the most recent database row after 'checkpoint'
        if (dbm.getDatabaseProductName().equals("MySQL")) {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            String update_stmt = "select crawl_set,insert_timestamp,UNCOMPRESS(crawl_data) as cdata from "
                    + this.instance_table + " where crawl_set>" + checkpoint + "  LIMIT 1";
            logger.log(Level.FINER, update_stmt);
            ResultSet rs = statement.executeQuery(update_stmt);

            boolean ret_rows = rs.first();

            if (!ret_rows) {
                logger.log(Level.FINER, "No Rows Returned.");
                connection.close();
                return null;
            }
            BigDecimal crawl_set = null;
            String crawl_data = null;
            while (ret_rows) {
                crawl_set = rs.getBigDecimal("crawl_set");
                //crawl_data = rs.getString("crawl_data");
                crawl_data = rs.getString("cdata");
                ret_rows = rs.next();
            }

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

            //BASE64 DECODE 
            byte[] byte_decoded_entry = org.apache.commons.codec.binary.Base64
                    .decodeBase64(crawl_data.getBytes());
            crawl_data = new String(byte_decoded_entry);

            logger.log(Level.INFO, "Returning from DBStore. Index Value: " + crawl_set.toPlainString());
            logger.log(Level.FINEST, "Returning from DBStore. " + crawl_data);
            DocListEntry dret = new DocListEntry(crawl_set.toPlainString(), crawl_data);
            return dret;
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Unable to retrieve docListEntry " + ex);
    }
    return new DocListEntry(checkpoint, null);
}

From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java

@Override
public void duplicateLayerTable(final String sourceTable, final String destinationTable) {
    SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory();
    final String schema = sfi.getSettings().getDefaultSchemaName();
    final String copyTableSql = MessageFormat.format(DUPLICATE_TABLE_SQL, schema, destinationTable,
            sourceTable);// ww  w  .  j  a v  a 2 s .c  o m

    final String updateGeometryColumnSql = String.format(UPDATE_GEOMETRY_COLUMN_SQL, destinationTable,
            sourceTable);

    getSession().doWork(new Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            Statement stmt = connection.createStatement();
            stmt.execute(copyTableSql);
            stmt.execute(updateGeometryColumnSql);
            ResultSet pksRS = connection.getMetaData().getPrimaryKeys(null, schema, sourceTable);

            if (pksRS.first()) {
                String primaryKey = pksRS.getString("COLUMN_NAME");

                String createPkSql = MessageFormat.format(ADD_TABLE_PK, schema, destinationTable, primaryKey);

                stmt.execute(createPkSql);
            }
        }
    });

    getSession().flush();
}

From source file:com.drevelopment.couponcodes.bukkit.coupon.BukkitCouponHandler.java

@Override
public Coupon getCoupon(String coupon) {
    if (!couponExists(coupon))
        return null;
    try {//from w ww.j  av a 2 s . c  o  m
        ResultSet rs = databaseHandler.query("SELECT * FROM couponcodes WHERE name='" + coupon + "'");
        if (databaseHandler.getDatabaseOptions() instanceof MySQLOptions)
            rs.first();
        int usetimes = rs.getInt("usetimes");
        int time = rs.getInt("timeuse");
        HashMap<String, Boolean> usedplayers = playerStringToHash(rs.getString("usedplayers"));

        if (rs.getString("ctype").equalsIgnoreCase("Item"))
            return createNewItemCoupon(coupon, usetimes, time, itemStringToHash(rs.getString("ids"), null),
                    usedplayers);
        else if (rs.getString("ctype").equalsIgnoreCase("Economy"))
            return createNewEconomyCoupon(coupon, usetimes, time, usedplayers, rs.getInt("money"));
        else if (rs.getString("ctype").equalsIgnoreCase("Rank"))
            return createNewRankCoupon(coupon, rs.getString("groupname"), usetimes, time, usedplayers);
        else if (rs.getString("ctype").equalsIgnoreCase("Xp"))
            return createNewXpCoupon(coupon, rs.getInt("xp"), usetimes, time, usedplayers);
        else if (rs.getString("ctype").equalsIgnoreCase("Command"))
            return createNewCommandCoupon(coupon, rs.getString("command"), usetimes, time, usedplayers);
        else
            return null;
    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java

/**
 * Verify that the user oauth token is valid, must be called after verifyConsumer as it has to look for both the user
 * token and the application id which it gets from verifyConsumer
 * @throws OAuthException Thrown if the user token is invalid
 *//*from w w w .ja va2  s  .  com*/
public void verifyOAuthToken(Database database) throws SQLException, OAuthException {
    final String oauth_token = oauth_params.get(OAuthParameters.OAUTH_TOKEN);
    PreparedStatement statement = database.getConnection().prepareStatement(SELECT_QUERY);
    statement.setInt(1, consumer.getId());
    statement.setString(2, oauth_token);
    ResultSet result = statement.executeQuery();
    if (result.first())
        user = new User(result);
    result.close();
    if (user == null)
        throw new OAuthException(ErrorMessages.INVALID_OAUTH_TOKEN);
}