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:com.chiorichan.database.SqlTable.java

protected Object toObject(Object clz, ResultSet rs) throws SQLException {
    Validate.notNull(clz);//from   w  w  w  . ja v  a 2  s .c  om
    Validate.notNull(rs);

    if (rs.getRow() == 0)
        rs.first();

    for (Field f : clz.getClass().getDeclaredFields()) {
        SqlColumn sc = f.getAnnotation(SqlColumn.class);

        try {
            if (sc != null && rs.getObject(sc.name()) != null) {
                Object obj = rs.getObject(sc.name());
                if (f.getType().equals(String.class)) {
                    f.set(clz, ObjectUtil.castToString(obj));
                } else if (obj instanceof String && (f.getType().equals(Long.class)
                        || f.getType().getSimpleName().equalsIgnoreCase("long"))) {
                    f.set(clz, Long.parseLong((String) obj));
                } else if (obj instanceof String && (f.getType().equals(Integer.class)
                        || f.getType().getSimpleName().equalsIgnoreCase("int"))) {
                    f.set(clz, Integer.parseInt((String) obj));
                } else {
                    f.set(clz, obj);
                }
            }
        } catch (IllegalArgumentException e) {
            Loader.getLogger()
                    .severe("We can't cast the value '" + rs.getObject(sc.name()) + "' from column `"
                            + sc.name() + "` with type `" + rs.getObject(sc.name()).getClass().getSimpleName()
                            + "` to FIELD `" + f.getName() + "` with type `" + f.getType() + "`.");
        } catch (IllegalAccessException e) {
            Loader.getLogger().severe("We don't have access to FIELD `" + f.getName()
                    + "`, Be sure the field has a PUBLIC modifier.");
        }
    }

    return clz;
}

From source file:oscar.dms.EDocUtil.java

public static EDoc getDocFromNote(Long noteId) {
    EDoc doc = new EDoc();
    Long docIdL = getTableIdFromNoteId(noteId);
    if (docIdL > 0L) {
        Integer docId = docIdL.intValue();
        String getDocSql = "select document_no, docfilename, status from document where document_no=" + docId;
        ResultSet rs = getSQL(getDocSql);
        try {//  ww w  .j ava  2  s  . com
            if (rs.first()) {
                doc.setDocId(rs.getString("document_no"));
                doc.setFileName(rs.getString("docfilename"));
                doc.setStatus(rs.getString("status").charAt(0));
            }
        } catch (SQLException ex) {
            logger.error("Error", ex);
        }
    }
    return doc;
}

From source file:com.orientechnologies.orient.jdbc.spring.CorenetThread.java

public void run() {
    try {//  www.  j ava2s .  c om
        PreparedStatement queryPrepStatement = connection
                .prepareStatement("SELECT FROM OGraphVertex WHERE name = ?");
        queryPrepStatement.setString(1, ROOT_VERTEX_NAME);
        ResultSet rs = queryPrepStatement.executeQuery();

        Assert.assertTrue(NAME + "There is no vertex with name " + ROOT_VERTEX_NAME, rs.first());
        //the RID is always the first element in the RS
        Object vertexId = rs.getObject(1);
        OrientGraph g = connection.unwrap(OrientGraph.class);
        Vertex v = g.getVertex(vertexId);
        Assert.assertNotNull(NAME + "There is no vertex for rid ", v);

        Iterator<Edge> containmentRels = v.getEdges(Direction.OUT, SUPPLY_RELATION_EDGE).iterator();
        Assert.assertTrue(
                NAME + "There is no edge with label '" + SUPPLY_RELATION_EDGE + "' coming from " + v.toString(),
                containmentRels.hasNext());

        String prefix = NAME + "Values:: ";
        StringBuilder textToBePrinted = new StringBuilder(prefix);
        Edge currentRel;
        while (containmentRels.hasNext()) {
            currentRel = containmentRels.next();
            if (textToBePrinted.length() == prefix.length())
                textToBePrinted.append(currentRel.getVertex(Direction.IN).getProperty("name").toString());
            else
                textToBePrinted
                        .append(", " + currentRel.getVertex(Direction.IN).getProperty("name").toString());
        }
        System.out.println(textToBePrinted);
    } catch (SQLException e) {
        e.printStackTrace();
        Assert.fail();
    }

}

From source file:com.mycompany.rubricatelefonica.DefaultUtenteDao.java

public UtenteModel getUtenteInfo(String email) {

    UtenteModel utenteModel = new UtenteModel();

    MysqlDataSource dataSource = new MysqlDataSource();

    dataSource.setUser("root");
    dataSource.setPassword("root");
    dataSource.setUrl("jdbc:mysql://localhost:3306/RubricaTelef");

    Connection conn = null;//w w  w  .  j  ava 2  s . c  o  m

    try {

        conn = dataSource.getConnection();

        PreparedStatement stmtUserInfo = conn.prepareStatement(USER_INFO);

        stmtUserInfo.setString(1, email);

        ResultSet rsUserInfoSet = stmtUserInfo.executeQuery();

        if (rsUserInfoSet.first()) {

            utenteModel.setNome(rsUserInfoSet.getString("nome"));
            utenteModel.setCognome(rsUserInfoSet.getString("cognome"));
            utenteModel.setEmail(rsUserInfoSet.getString("email"));
            utenteModel.setNumCell(rsUserInfoSet.getString("numCell"));
        }

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("errore!! Connessione Fallita");
    } finally {

        DbUtils.closeQuietly(conn); //oppure try with resource
    }

    return utenteModel;
}

From source file:com.orientechnologies.orient.jdbc.spring.IoTatWorkThread.java

public void run() {
    try {//w  w w  .j av a 2  s.c o  m
        PreparedStatement queryPrepStatement = connection
                .prepareStatement("SELECT FROM OGraphVertex WHERE name = ?");
        queryPrepStatement.setString(1, ROOT_VERTEX_NAME);
        ResultSet rs = queryPrepStatement.executeQuery();

        Assert.assertTrue(NAME + "There is no vertex with name " + ROOT_VERTEX_NAME, rs.first());
        //the RID is always the first element in the RS
        Object vertexId = rs.getObject(1);
        OrientGraph g = connection.unwrap(OrientGraph.class);
        Vertex v = g.getVertex(vertexId);

        Iterator<Edge> categories = v.getEdges(Direction.OUT, "category").iterator();
        Edge categoryEdge;
        Vertex aggregationV = null;
        while (categories.hasNext() && aggregationV == null) {
            categoryEdge = categories.next();
            if (categoryEdge.getVertex(Direction.IN).getProperty("name").equals("Aggregation"))
                aggregationV = categoryEdge.getVertex(Direction.IN);
        }
        Assert.assertNotNull("Missing aggregation category", aggregationV);
        Iterator<Edge> containmentRels = aggregationV.getEdges(Direction.OUT, CONTAINMENT_RELATION_EDGE)
                .iterator();
        Assert.assertTrue(NAME + "There is no edge with label '" + CONTAINMENT_RELATION_EDGE + "' coming from "
                + v.toString(), containmentRels.hasNext());

        String prefix = NAME + "Values:: ";
        StringBuilder textToBePrinted = new StringBuilder(prefix);
        Edge currentRel;
        while (containmentRels.hasNext()) {
            currentRel = containmentRels.next();
            if (textToBePrinted.length() == prefix.length())
                textToBePrinted.append(currentRel.getVertex(Direction.IN).getProperty("name").toString());
            else
                textToBePrinted
                        .append(", " + currentRel.getVertex(Direction.IN).getProperty("name").toString());
        }
        System.out.println(textToBePrinted);
    } catch (SQLException e) {
        e.printStackTrace();
        Assert.fail();
    }

}

From source file:com.mycompany.rubricatelefonica.DefaultUtenteDao.java

public UtenteModel getUtenteSmartphone(String email) {

    SmartphoneModel smartphoneModel = new SmartphoneModel();

    UtenteModel utenteModel = new UtenteModel();

    MysqlDataSource dataSource = new MysqlDataSource();

    dataSource.setUser("root");
    dataSource.setPassword("root");
    dataSource.setUrl("jdbc:mysql://localhost:3306/RubricaTelef");

    Connection conn = null;//from w ww . j a  v a  2s. c o  m

    try {

        conn = dataSource.getConnection();

        PreparedStatement stmtUserInfo = conn.prepareStatement(USER_SMARTH_INFO);

        stmtUserInfo.setString(1, email);

        ResultSet rsUserInfoSet = stmtUserInfo.executeQuery();

        if (rsUserInfoSet.first()) {

            utenteModel.setNome(rsUserInfoSet.getString("nome"));
            utenteModel.setCognome(rsUserInfoSet.getString("cognome"));
            utenteModel.setEmail(rsUserInfoSet.getString("email"));
            smartphoneModel.setMarca(rsUserInfoSet.getString("marca"));
            smartphoneModel.setModello(rsUserInfoSet.getString("modello"));
            utenteModel.setSmartphone(smartphoneModel);
        }

    } catch (SQLException e) {
        System.out.println(e.getMessage());
        System.out.println("errore!! Connessione Fallita");
    } finally {

        DbUtils.closeQuietly(conn); //oppure try with resource
    }

    return utenteModel;

}

From source file:org.wso2.authenticator.jdbc.JDBCAuthenticator.java

/**
 * @see org.wso2.usermanager.Authenticator#authenticate(String, Object)
 *//*  w w w .  j  a  v  a2  s .c o  m*/
public boolean authenticate(String userName, Object credentials) throws AuthenticatorException {

    if (credentials == null) {
        return false;
    }

    if (userName == null) {
        return false;
    }

    boolean bValue = false;

    if (!(credentials instanceof String)) {
        throw new AuthenticatorException("Can handle only string type credentials");
    } else {
        try {
            this.open();
            String password = (String) credentials;
            String stmtValue = this.constructSQLtoReadPassword(userName);

            if (log.isDebugEnabled()) {
                log.debug(stmtValue);
            }

            Statement stmt = dbConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);

            ResultSet rs = stmt.executeQuery(stmtValue);

            if (rs.first() == true) {
                String value = rs.getString(userCredentialColumn);
                if ((value != null) && (value.equals(password))) {
                    bValue = true;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
            throw new AuthenticatorException("exceptionOnAuthenticate");
        }
    }
    return bValue;
}

From source file:ueg.watchdog.model.Video.java

public boolean save() {
    String query = "INSERT INTO `" + TABLE
            + "` (file_name,processed,file_path,start_time,end_time,deleted) VALUES(?,?,?,?,?,?)";
    Connection connection = DbConnect.getDBConnection();
    try {/*from  w  ww. j av  a  2 s  .  com*/
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setString(1, getFileName());
        statement.setBoolean(2, isProcessed());
        statement.setString(3, getFilePath());
        statement.setTimestamp(4, WatchDogUtils.toMySQLDate(getFrom()));
        statement.setTimestamp(5, WatchDogUtils.toMySQLDate(getTo()));
        statement.setBoolean(6, false);
        statement.execute();
        String fetchIdQuery = "SELECT `id` FROM `" + TABLE + "` ORDER BY `id`  DESC LIMIT 1";
        PreparedStatement fetchIdStatement = connection.prepareStatement(fetchIdQuery);
        ResultSet resultSet = fetchIdStatement.executeQuery();
        resultSet.first();
        this.id = resultSet.getInt("id");
    } catch (SQLException e) {
        logger.error("Error occurred when saving video ({},{}) details to DB", getFileName(), getFilePath(), e);
        return false;
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return true;
}

From source file:oscar.dms.EDocUtil.java

public static EDoc getEDocFromDocId(String docId) {
    String sql = "SELECT DISTINCT c.module, c.module_id, d.doccreator, d.source, d.sourceFacility, d.responsible, d.program_id, "
            + "d.status, d.docdesc, d.docfilename, d.doctype, d.document_no, d.updatedatetime, d.contenttype, d.observationdate, "
            + "d.docClass, d.docSubClass, d.reviewer, d.reviewdatetime, d.appointment_no "
            + "FROM document d, ctl_document c " + "WHERE c.document_no=d.document_no AND c.document_no='"
            + docId + "'";
    sql = sql + " ORDER BY " + EDocUtil.SORT_OBSERVATIONDATE;// default sort

    ResultSet rs = getSQL(sql);
    EDoc currentdoc = new EDoc();
    try {/*w  ww  .  j a va 2s . c om*/
        if (rs.first()) {

            currentdoc.setModule(rsGetString(rs, "module"));
            currentdoc.setModuleId(rsGetString(rs, "module_id"));
            currentdoc.setDocId(rsGetString(rs, "document_no"));
            currentdoc.setDescription(rsGetString(rs, "docdesc"));
            currentdoc.setType(rsGetString(rs, "doctype"));
            currentdoc.setDocClass(rsGetString(rs, "docClass"));
            currentdoc.setDocSubClass(rsGetString(rs, "docSubClass"));
            currentdoc.setCreatorId(rsGetString(rs, "doccreator"));
            currentdoc.setSource(rsGetString(rs, "source"));
            currentdoc.setSourceFacility(rsGetString(rs, "sourceFacility"));
            currentdoc.setResponsibleId(rsGetString(rs, "responsible"));
            String temp = rsGetString(rs, "program_id");
            if (temp != null && temp.length() > 0)
                currentdoc.setProgramId(Integer.valueOf(temp));
            temp = rsGetString(rs, "appointment_no");
            if (temp != null && temp.length() > 0)
                currentdoc.setAppointmentNo(Integer.valueOf(temp));

            currentdoc.setDateTimeStampAsDate(rs.getTimestamp("updatedatetime"));
            currentdoc.setDateTimeStamp(rsGetString(rs, "updatedatetime"));
            currentdoc.setFileName(rsGetString(rs, "docfilename"));
            currentdoc.setStatus(rsGetString(rs, "status").charAt(0));
            currentdoc.setContentType(rsGetString(rs, "contenttype"));
            currentdoc.setObservationDate(rsGetString(rs, "observationdate"));
            currentdoc.setReviewerId(rsGetString(rs, "reviewer"));
            currentdoc.setReviewDateTime(rsGetString(rs, "reviewdatetime"));
            currentdoc.setReviewDateTimeDate(rs.getTimestamp("reviewdatetime"));

            rs.close();
        }
    } catch (SQLException sqe) {
        logger.error("Error", sqe);
    }

    return currentdoc;
}

From source file:org.owasp.webgoat.plugin.CrossSiteScriptingLesson5b.java

protected AttackResult injectableQuery(String accountName) {
    try {/*w w w  .j  ava2 s .  c om*/
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE userid = " + accountName;

        try {
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet results = statement.executeQuery(query);

            if ((results != null) && (results.first() == true)) {
                ResultSetMetaData resultsMetaData = results.getMetaData();
                StringBuffer output = new StringBuffer();

                output.append(writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 6) {
                    return trackProgress(AttackResult.success("You have succeed: " + output.toString()));
                } else {
                    return trackProgress(AttackResult.failed("You are close, try again. " + output.toString()));
                }

            } else {
                return trackProgress(AttackResult.failed("No Results Matched. Try Again. "));

                //                    output.append(getLabelManager().get("NoResultsMatched"));
            }
        } catch (SQLException sqle) {

            return trackProgress(AttackResult.failed(sqle.getMessage()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        return trackProgress(
                AttackResult.failed("ErrorGenerating" + this.getClass().getName() + " : " + e.getMessage()));
    }
}