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:ueg.watchdog.model.Video.java

public static Video getVideoById(int id) {
    String query = "SELECT * FROM `" + TABLE + "` WHERE id=?";
    Connection connection = DbConnect.getDBConnection();
    try {/*  w  w  w  .j a v  a 2 s .  c  o m*/
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setInt(1, id);
        ResultSet resultSet = statement.executeQuery();
        resultSet.first();
        return loadData(resultSet);
    } catch (SQLException e) {
        logger.error("Error occurred when fetching video with id : {} from DB", id, e);
        return null;
    } finally {
        DbUtils.closeQuietly(connection);
    }
}

From source file:org.mskcc.cbio.portal.dao.MySQLbulkLoader.java

/**
 * Flushes all pending data from the bulk writer. Temporarily disables referential
 * integrity while it does so, largely because MySQL uses a weird model and expects
 * referential integrity at each record, not just at the end of the transaction.
 * @return the number of rows added//  w w w .j  av  a2 s . c om
 * @throws DaoException
 */
public static int flushAll() throws DaoException {
    int checks = 0;
    PreparedStatement stmt = null;
    boolean executedSetFKChecks = false;
    try {
        Connection con = JdbcUtil.getDbConnection(MySQLbulkLoader.class);
        stmt = con.prepareStatement("SELECT @@foreign_key_checks;");
        ResultSet result = stmt.executeQuery();

        result.first();
        checks = result.getInt(1);

        stmt = con.prepareStatement("SET foreign_key_checks = ?;");
        stmt.setLong(1, 0);
        stmt.execute();
        executedSetFKChecks = true;

        int n = 0;
        for (MySQLbulkLoader mySQLbulkLoader : mySQLbulkLoaders.values()) {
            n += mySQLbulkLoader.loadDataFromTempFileIntoDBMS();
        }

        return n;
    } catch (IOException e) {
        System.err.println("Could not open temp file");
        e.printStackTrace();
        return -1;
    } catch (SQLException e) {
        throw new DaoException(e);
    } finally {
        mySQLbulkLoaders.clear();
        if (executedSetFKChecks && stmt != null) {
            try {
                stmt.setLong(1, checks);
                stmt.execute();
            } catch (SQLException e) {
                throw new DaoException(e);
            }

        }
    }
}

From source file:utilities.PayPal.java

/**
 * Dynamically builds the PayPal form with PayPal's paypal-button.min.js library,
 * it passed the amount,charity name and optional article id with the callback url for when the transaction is 
 * complete and returned to the DonationManager.java servlet, which extracts the parameters
 * and logs them in the database./*from   ww w  .j av a 2  s.  c om*/
 * 
 * 
 * @param request The HttpServletRequest to identify the charity logged in
 * @param out     The PrintWriter to send the html back to the browser 
 */
public static void buildPayPalForm(HttpServletRequest request, PrintWriter out) {

    String merchantIDorEmail = "";
    String returnUrl = "http://localhost:8080/cs3305/DonationManager";
    //String callbackUrl     = "http://localhost:8080/cs3305/HomePage.html";
    String cancelReturnUrl = "http://localhost:8080/cs3305/HomePage.html";
    String amount = "10.00";
    String currency = "EUR";

    HttpSession session = request.getSession(true);
    String charityName = (String) session.getAttribute("charityName");
    String article_id = (request.getParameter("article_id") == null) ? "0" : request.getParameter("article_id");
    int charityID = 0;

    //Connect to Database
    DBConnect dbConnect = new DBConnect();
    Connection connection = dbConnect.getConnection();

    String selectCharityID = "SELECT   id " + "FROM   charities " + "WHERE  name = ?";

    try (PreparedStatement selectIDStatement = connection.prepareStatement(selectCharityID)) {
        selectIDStatement.setString(1, charityName);
        ResultSet charityIDResultSet = selectIDStatement.executeQuery();

        if (charityIDResultSet.first()) {
            charityID = charityIDResultSet.getInt(1);
        }
    } catch (SQLException ex) {

    }
    if (DEBUG_ON) {
        System.out.println("CharityID :" + charityID);
    }

    if (charityID > 0) {

        String stringInputAmount = request.getParameter("amount");
        if (DEBUG_ON) {
            System.out.println("Submitted Amount :" + stringInputAmount);
        }
        if (stringInputAmount != null && !"".equals(stringInputAmount)) {
            int intInputAmount = Integer.valueOf(stringInputAmount);
            if (intInputAmount > 0) {
                amount = String.valueOf(intInputAmount);
            }
        }

        String inputCurrency = request.getParameter("currency");
        if (inputCurrency != null && !"".equals(inputCurrency)) {
            if (inputCurrency.equalsIgnoreCase("EUR")) {
                currency = "EUR";
            } else if (inputCurrency.equalsIgnoreCase("USD")) {
                currency = "USD";
            } else if (inputCurrency.equalsIgnoreCase("GBP")) {
                currency = "GBP";
            } else if (inputCurrency.equalsIgnoreCase("CNY")) {
                currency = "CNY";
            }

            if (DEBUG_ON) {
                System.out.println("Submitted Currency :" + currency);
            }
        }
        String selectPayPalEmail = "SELECT paypal_email " + "FROM   charities " + "WHERE  id = ?";
        try {
            PreparedStatement payPalStatement = connection.prepareStatement(selectPayPalEmail);
            payPalStatement.setInt(1, Integer.valueOf(charityID));
            ResultSet payPalResultSet = payPalStatement.executeQuery();

            if (payPalResultSet.next()) {
                merchantIDorEmail = payPalResultSet.getString(1);
            }

            if (DEBUG_ON) {
                System.out.println("MerchantIDorEmail : " + merchantIDorEmail);
            }
        } catch (SQLException ex) {
            Logger.getLogger(PayPal.class.getName()).log(Level.SEVERE, null, ex);
        }

        /* Encoding the values as a security measure, in a real deployment the should be encrypted */
        byte[] encodedAmountinBytes = Base64.encodeBase64(amount.getBytes());
        byte[] encodedCharityIDinBytes = Base64.encodeBase64(new Integer(charityID).toString().getBytes());
        String encodedAmount = new String(encodedAmountinBytes);
        String encodedCharityID = new String(encodedCharityIDinBytes);

        if (merchantIDorEmail != null && !"".equals(merchantIDorEmail)) {

            returnUrl = returnUrl.concat("?amount=" + encodedAmount).concat("&charity_id=" + encodedCharityID);
            if (!"0".equals(article_id)) {
                returnUrl = returnUrl.concat("&article_id=" + article_id);
            }
            System.out.println(returnUrl);

            /* Uses Paypals https://www.paypalobjects.com/js/external/paypal-button.min.js 
             * Which automatically generates the paypal donate button with the attributes given to the script, which
             * can be viewed below
             */
            out.println("<article class='paypal_form'>");
            out.println("<h1>Review Donation</h1>");
            out.println("<p>Dontaion Amount : " + amount + "</p>");
            out.println("<p>Currency        : " + currency + "</p>");
            out.println("<script src='https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant="
                    + merchantIDorEmail + "' ");
            out.println("data-button='donate' ");
            out.println("data-name='" + charityName + " Donation' ");
            out.println("data-amount='" + amount + "' ");
            out.println("data-currency='" + currency + "' ");
            out.println("data-shipping='0' ");
            out.println("data-tax='0' ");
            out.println("data-rm='2' ");
            out.println("data-cancel_return='" + cancelReturnUrl + "' ");
            //out.println("data-custom='amount=" + encodedAmount + "&charity_id='" + encodedCharityID + " ");
            //out.println("data-callback='" + callbackUrl + "' ");
            out.println("data-return='" + returnUrl + "' ");
            out.println("data-env='sandbox'");
            out.println("></script>");
            out.println("</article>");
        } else {
            out.println("<article class='paypal_form'>");
            out.println("<p>This Charity does not have a PayPal account Setup.</p>");
            out.println("</article>");
        }
    } else {
        out.println("<article class='paypal_form'>");
        out.println("<p>A problem has occured, please refresh the page and try again.</p>");
        out.println("</article>");
    }
}

From source file:org.lsst.camera.portal.queries.SensorUtils.java

public static String getHardwareTypeFromId(HttpSession session, String lsstNum) throws SQLException {
    Connection c = null;/* w  ww  .ja  va 2 s  .  c o m*/

    try {
        c = ConnectionManager.getConnection(session);

        PreparedStatement idStatement = c.prepareStatement("SELECT HT.name FROM "
                + "Hardware H INNER JOIN HardwareType HT ON H.hardwareTypeId = HT.id " + "WHERE H.lsstId=?");
        idStatement.setString(1, lsstNum);
        ResultSet r = idStatement.executeQuery();
        if (r.first())
            return r.getString("name").toUpperCase();
        else
            return null;
    } catch (Exception e) {
        return null;
    } finally {
        if (c != null) {
            c.close();
        }

    }
}

From source file:org.lsst.camera.portal.queries.SensorUtils.java

public static SensorSummary processSensor(Map.Entry<String, Object> entry, Map<String, Object> allCteJhData,
        Connection c, HttpSession session, int reportId, Specifications specs) throws SQLException {
    SensorSummary sensorData = null;//from www .ja v  a2  s .co  m
    DecimalFormat df = new DecimalFormat("##.#");

    try {
        // Pull out CTE data if available
        Map<String, Object> curCte = (Map<String, Object>) allCteJhData.get(entry.getKey());
        Integer hid = (Integer) curCte.get("hid");
        ArrayList<Map<String, Object>> curCteSchema = extractSchema(
                (Map<String, Object>) allCteJhData.get(entry.getKey()), entry.getKey(), "cte", "cte");
        Map<Integer, String> worstHCTI = getWorstCTI(curCteSchema, "cti_low_serial", "cti_high_serial");
        Map<Integer, String> worstVCTI = getWorstCTI(curCteSchema, "cti_low_parallel", "cti_high_parallel");

        Integer parentActId = 0;
        ArrayList<Map<String, Object>> curSchema = extractSchema((Map<String, Object>) entry.getValue(),
                entry.getKey(), "read_noise", "read_noise");
        double max_read_noise = 0.0d;
        int max_amp = 0;
        for (Object obj : curSchema) {
            Map<String, Object> m = (Map<String, Object>) obj;
            if ((Integer) m.get("schemaInstance") == 0) {
                continue;
            }
            parentActId = (Integer) m.get("activityId");
            Double read_noise = (Double) m.get("read_noise");
            Integer amp = (Integer) m.get("amp");
            if (read_noise > max_read_noise) {
                max_read_noise = read_noise;
                max_amp = amp;
            }

        }
        // Use the parentActId to extract the results of all the eotest specs and get a count
        int numTestsPassed = -999;
        String percentDefects = "NA";
        Boolean passedReadNoise = false;
        Boolean passedHCTI = false;
        Boolean passedVCTI = false;
        Boolean passedPercentDefects = false;
        int actIdForSpecs = 0;
        if (parentActId > 0) {
            PreparedStatement parentActIdS = c
                    .prepareStatement("select parentActivityId FROM Activity WHERE id=?");
            parentActIdS.setInt(1, parentActId);
            ResultSet r = parentActIdS.executeQuery();
            if (r.first()) {
                actIdForSpecs = r.getInt("parentActivityId");
            }
            Map<String, Map<String, List<Object>>> theMap = SummaryUtils.getReportValues(session, actIdForSpecs,
                    reportId);

            numTestsPassed = getTotalTestsPassed(theMap, specs);
            passedReadNoise = getTestResult(theMap, specs, "CCD-007");
            passedVCTI = getTestResult(theMap, specs, "CCD-011");
            passedHCTI = getTestResult(theMap, specs, "CCD-010");
            passedPercentDefects = getTestResult(theMap, specs, "CCD-012");

            percentDefects = getPercentDefects(session, theMap, specs);
        }

        sensorData = new SensorSummary();
        sensorData.setLsstId(entry.getKey());
        sensorData.setHardwareId(hid);
        sensorData.setMaxReadNoiseChannel(max_amp);
        sensorData.setMaxReadNoise(Double.parseDouble(df.format(max_read_noise)));
        sensorData.setNumTestsPassed(numTestsPassed);
        sensorData.setPercentDefects(percentDefects);
        if (worstHCTI != null) {
            sensorData.setWorstHCTIChannel((Integer) worstHCTI.keySet().iterator().next());
            sensorData.setWorstHCTI((String) worstHCTI.values().iterator().next());
        }
        if (worstVCTI != null) {
            sensorData.setWorstVCTIChannel((Integer) worstVCTI.keySet().iterator().next());
            sensorData.setWorstVCTI((String) worstVCTI.values().iterator().next());
        }
        sensorData.setPassedReadNoise(passedReadNoise);
        sensorData.setPassedHCTI(passedHCTI);
        sensorData.setPassedVCTI(passedVCTI);
        sensorData.setPassedPercentDefects(passedPercentDefects);
    } catch (Exception e) {
        logger.log(Level.WARNING, "**Error while creating Sensor Summary Table: ", e);
    }
    return (sensorData);
}

From source file:oscar.util.UtilMisc.java

public static String[][] getArrayFromResultSet(ResultSet rs) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    ArrayList rows = new ArrayList();
    ArrayList cols = new ArrayList();
    for (int i = 0; i < columns; i++) { // for each column in result set
        cols.add(rsmd.getColumnName(i + 1));
    }/*from ww  w.  j  a  va2s.co  m*/
    rows.add(cols);
    rs.first();
    do {
        cols = new ArrayList();
        for (int j = 0; j < columns; j++) {
            cols.add(oscar.Misc.getString(rs, j + 1));
        }
        rows.add(cols);
    } while (rs.next());
    String[][] data = new String[rows.size()][columns];
    for (int i = 0; i < rows.size(); i++) {
        data[i] = (String[]) ((ArrayList) rows.get(i)).toArray(data[i]);
    }
    return data;
}

From source file:op.OPDE.java

public static int getDBVersion(Connection jdbcConnection) {
    int version = -1;
    try {//from  w  ww .java 2s.c  o  m
        String query = " SELECT p.V FROM sysprops p WHERE p.K = ? ";
        PreparedStatement stmt = jdbcConnection.prepareStatement(query);
        stmt.setString(1, "dbstructure");
        ResultSet rs = stmt.executeQuery();

        if (rs.first()) {
            String v = rs.getString("V");
            version = Integer.parseInt(v);
        }

    } catch (SQLException e) {
        fatal(e);
    }
    return version;
}

From source file:ece356.UserDBAO.java

public static FriendShipStatus addFriend(String friendA, String friendB)
        throws ClassNotFoundException, SQLException, NamingException {
    Connection con = null;//from  w  w w  .  java 2 s  . com
    PreparedStatement pstmt = null;
    try {
        con = getConnection();
        // First check if sender has already sent a request to receiver in the past
        // If he has, then check if it's accepted
        // If it is accepted, then return ALREADY_FRIENDS
        // If it is not accepted, then return WAITING_FOR_ACCEPT
        // If he hasn't then check if the receiver has sent a request to sender in the past
        // If he hasn't, then make an INSERT and return REQUEST_SENT
        // If he has, then check if it's accepted
        // If it's not accepted, then UPDATE and make isAccepted = true and return FRIENDSHIP_ESTABLISHED                            
        // If it is accepted, then return ALREADY_FRIENDS                        

        // Find if this request is already there
        String query = "SELECT * FROM friend where sent_username = ? AND recieved_username = ?";
        pstmt = con.prepareStatement(query);
        pstmt.setString(1, friendA);
        pstmt.setString(2, friendB);

        ResultSet resultSet;
        resultSet = pstmt.executeQuery();
        resultSet.next();

        if (resultSet.first()) {
            System.out.println("RESULT SET: " + resultSet.getString("sent_username") + " "
                    + resultSet.getString("recieved_username"));
            boolean isAccepted = resultSet.getBoolean("isAccepted");
            if (isAccepted) {
                return FriendShipStatus.ALREADY_FRIENDS;
            } else {
                return FriendShipStatus.WAITING_FOR_ACCEPT;
            }
        } else {
            pstmt = con.prepareStatement(query);
            pstmt.setString(1, friendB);
            pstmt.setString(2, friendA);
            resultSet = pstmt.executeQuery();
            resultSet.next();
            if (resultSet.first()) {
                System.out.println("RESULT SET: " + resultSet.getString("sent_username") + " "
                        + resultSet.getString("recieved_username"));
                boolean isAccepted = resultSet.getBoolean("isAccepted");
                if (isAccepted) {
                    return FriendShipStatus.ALREADY_FRIENDS;
                } else {
                    String update = "UPDATE friend SET isAccepted = ? where sent_username = ? AND recieved_username = ?;";
                    pstmt = con.prepareStatement(update);
                    pstmt.setBoolean(1, true);
                    pstmt.setString(2, friendB);
                    pstmt.setString(3, friendA);
                    pstmt.executeUpdate();
                    return FriendShipStatus.FRIENDSHIP_ESTABLISHED;
                }
            } else {
                pstmt = con.prepareStatement(
                        "INSERT INTO friend (sent_username, recieved_username) VALUES (?, ?);");
                pstmt.setString(1, friendA);
                pstmt.setString(2, friendB);
                pstmt.executeUpdate();
                return FriendShipStatus.REQUEST_SENT;
            }
        }
    } finally {
        if (pstmt != null) {
            pstmt.close();
        }
        if (con != null) {
            con.close();
        }
    }
}

From source file:oscar.oscarLab.ca.all.Hl7textResultsData.java

public static LabResultData getNotAckLabResultDataFromLabNo(String labNo) {
    LabResultData lbData = new LabResultData(LabResultData.HL7TEXT);
    String sql = "";
    try {//from  w ww .ja  va2s.  c  om

        // note to self: lab reports not found in the providerLabRouting table will not show up - need to ensure every lab is entered in providerLabRouting, with '0'
        // for the provider number if unable to find correct provider

        sql = "select info.lab_no, info.sex, info.health_no, info.result_status, info.obr_date, info.priority, info.requesting_client, info.discipline, info.last_name, "
                + "info.first_name, info.report_status, info.accessionNum, info.final_result_count "
                + "from hl7TextInfo info " + " where info.lab_no = " + labNo + " ORDER BY info.obr_date DESC";

        logger.debug(sql);
        ResultSet rs = DBHandler.GetSQL(sql);
        if (rs.first()) {

            if (logger.isDebugEnabled()) {
                int columns = rs.getMetaData().getColumnCount();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < columns; i++) {
                    sb.append(rs.getString(i + 1));
                    sb.append(", ");
                }
                logger.debug("Record found : " + sb.toString());
            }

            lbData.labType = LabResultData.HL7TEXT;
            lbData.segmentID = oscar.Misc.getString(rs, "lab_no");
            //check if any demographic is linked to this lab
            if (lbData.isMatchedToPatient()) {
                //get matched demographic no
                String sql2 = "select * from patientLabRouting plr where plr.lab_no="
                        + Integer.parseInt(lbData.segmentID) + " and plr.lab_type='" + lbData.labType + "'";
                logger.debug("sql2=" + sql2);
                ResultSet rs2 = DBHandler.GetSQL(sql2);
                if (rs2.next())
                    lbData.setLabPatientId(oscar.Misc.getString(rs2, "demographic_no"));
                else
                    lbData.setLabPatientId("-1");
            } else {
                lbData.setLabPatientId("-1");
            }
            lbData.acknowledgedStatus = "U";
            lbData.accessionNumber = oscar.Misc.getString(rs, "accessionNum");
            lbData.healthNumber = oscar.Misc.getString(rs, "health_no");
            lbData.patientName = oscar.Misc.getString(rs, "last_name") + ", "
                    + oscar.Misc.getString(rs, "first_name");
            lbData.sex = oscar.Misc.getString(rs, "sex");

            lbData.resultStatus = oscar.Misc.getString(rs, "result_status");
            if (lbData.resultStatus.equals("A"))
                lbData.abn = true;

            lbData.dateTime = oscar.Misc.getString(rs, "obr_date");

            //priority
            String priority = oscar.Misc.getString(rs, "priority");

            if (priority != null && !priority.equals("")) {
                switch (priority.charAt(0)) {
                case 'C':
                    lbData.priority = "Critical";
                    break;
                case 'S':
                    lbData.priority = "Stat/Urgent";
                    break;
                case 'U':
                    lbData.priority = "Unclaimed";
                    break;
                case 'A':
                    lbData.priority = "ASAP";
                    break;
                case 'L':
                    lbData.priority = "Alert";
                    break;
                default:
                    lbData.priority = "Routine";
                    break;
                }
            } else {
                lbData.priority = "----";
            }

            lbData.requestingClient = oscar.Misc.getString(rs, "requesting_client");
            lbData.reportStatus = oscar.Misc.getString(rs, "report_status");

            // the "C" is for corrected excelleris labs
            if (lbData.reportStatus != null
                    && (lbData.reportStatus.equals("F") || lbData.reportStatus.equals("C"))) {
                lbData.finalRes = true;
            } else {
                lbData.finalRes = false;
            }

            lbData.discipline = oscar.Misc.getString(rs, "discipline");
            lbData.finalResultsCount = rs.getInt("final_result_count");

        }
        rs.close();
    } catch (Exception e) {
        logger.error("exception in getNotAckLabResultDataFromLabNo:", e);
    }
    return lbData;
}

From source file:net.mms_projects.copy_it.api.http.pages.v1.UserProfile.java

public FullHttpResponse onGetRequest(HttpRequest request, Database database, HeaderVerifier headerVerifier)
        throws Exception {
    PreparedStatement statement = database.getConnection().prepareStatement(SELECT_USER);
    statement.setInt(1, headerVerifier.getUserId());
    ResultSet result = statement.executeQuery();
    if (result.first()) {
        final JSONObject json = new JSONObject();
        json.put(ID, result.getInt(ID));
        json.put(EMAIL, result.getString(EMAIL));
        json.put(SIGNED_UP, result.getInt(SIGNED_UP));
        result.close();//  w w  w . jav a2s .c o  m
        return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
    }
    result.close();
    return null;
}