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.ProcessedFrameStat.java

public boolean save() {
    String query = "INSERT INTO `" + TABLE
            + "` (video_id,occurred_timestamp,description,face,profile_id) VALUES(?,?,?,?,?)";
    Connection connection = DbConnect.getDBConnection();
    try {//from   w  ww. j  av  a  2 s. c  om
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setInt(1, getVideoId());
        statement.setTimestamp(2, WatchDogUtils.toMySQLDate(getTimestamp()));
        statement.setString(3, getDescription());
        statement.setBinaryStream(4, ImageUtils.toInputStream(getFace()));
        statement.setString(5, getProfileId());
        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 (Exception e) {
        logger.error("Error occurred when saving stat to database", e);
        return false;
    } finally {
        DbUtils.closeQuietly(connection);
    }
    logger.debug("Successfully saved processed frame stats");
    return true;
}

From source file:com.uiip.gviviani.esercizioweekend.interfaces.impl.DefaultPersonDAO.java

@Override
public PersonModel getPersonInfo(String numero) {
    PersonModel personModel = new PersonModel();
    PhoneModel phone = new PhoneModel();
    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("root");
    datasource.setUrl("jdbc:mysql://localhost:3306/Rubrica");
    Connection connection = null;
    try {/*from   www  . jav  a2 s . c  o m*/
        connection = datasource.getConnection();
        String sql = "SELECT c.nome, c.cognome, c.data_nascita, t.name "
                + "FROM contatti c INNER JOIN telefono t ON (c.modello = t.id)" + "WHERE c.numero = ? ;";
        PreparedStatement stat = connection.prepareStatement(sql);
        stat.setString(1, numero);
        ResultSet res = stat.executeQuery();
        if (res.first()) {
            personModel.setNome(res.getString("nome"));
            personModel.setCognome(res.getString("cognome"));
            personModel.setData(res.getString("data_nascita"));
            personModel.setNumero(numero);
            phone.setNome(res.getString("name"));
            personModel.setModel(phone);
        } else {
            personModel = null;
        }
    } catch (SQLException e) {
        logger.error(e);
        personModel = null;
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return personModel;
}

From source file:com.uiip.gviviani.esercizioweekend.interfaces.impl.DefaultPersonDAO.java

@Override
public boolean inserisciPerson(PersonModel person, String nomeTel) {
    MysqlDataSource datasource = new MysqlDataSource();
    datasource.setUser("root");
    datasource.setPassword("root");
    datasource.setUrl("jdbc:mysql://localhost:3306/Rubrica");
    Connection connection = null;
    try {/*w  ww  . j ava 2 s .c  o  m*/
        connection = datasource.getConnection();
        String sql = "INSERT INTO contatti (nome, cognome, data_nascita, numero, modello) VALUE "
                + "(?, ?, ?, ?, ?);";
        int id;
        String sql2 = "SELECT id FROM telefono WHERE name = ? ;";
        PreparedStatement stat2 = connection.prepareStatement(sql2);
        stat2.setString(1, nomeTel);
        ResultSet res = stat2.executeQuery();
        if (res.first()) {
            id = res.getInt("id");
            PreparedStatement stat = connection.prepareStatement(sql);
            stat.setString(1, person.getNome());
            stat.setString(2, person.getCognome());
            stat.setString(3, person.getData());
            stat.setString(4, person.getNumero());
            stat.setInt(5, id);
            if (stat.executeUpdate() > 0) {
                return true;
            }
        }
    } catch (SQLException e) {
        logger.error(e);
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return false;
}

From source file:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson5b.java

protected AttackResult injectableQuery(String accountName) {
    try {/*from   w w w. ja  v a 2s . c o m*/
        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(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
                results.last();

                // If they get back more than one user they succeeded
                if (results.getRow() >= 6) {
                    return trackProgress(success().feedback("sql-injection.5b.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }

            } else {
                return trackProgress(failed().feedback("sql-injection.5b.no.results").build());

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

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

From source file:org.apache.hadoop.hive.ql.metadata.MetaStore.java

public String getPwd(Connection cc, String uname) {
    if (cc == null || uname == null) {
        return null;
    }/*from   w  w w. ja v a2 s.c o  m*/
    String rt = null;
    PreparedStatement pstmt;
    try {
        pstmt = cc.prepareStatement(" select PASSWD from USER where USER_NAME= ? ");
        pstmt.setString(1, uname);
        ResultSet rs = pstmt.executeQuery();
        rs.first();
        rt = (String) rs.getObject(1);
        rs.close();
        LOG.info(" get user pwd: " + uname + " " + rt);
    } catch (SQLException e) {
        LOG.error(" get user pwd failed: " + uname);
        e.printStackTrace();
    }
    return rt;
}

From source file:org.apache.hadoop.hive.ql.metadata.MetaStore.java

public String getDB(Connection cc, String dbname) {
    if (cc == null || dbname == null) {
        return null;
    }/*from  w  w w  .  j a  v  a2  s .c  o m*/
    String rt = null;
    PreparedStatement pstmt;
    try {
        pstmt = cc.prepareStatement(" select * from DBS where NAME= ? ");
        pstmt.setString(1, dbname);
        ResultSet rs = pstmt.executeQuery();
        rs.first();
        LOG.info((Long) rs.getObject(1));
        LOG.info((String) rs.getObject(2));
        rt = (String) rs.getObject(2);
        rs.close();
        LOG.info(" get db: " + dbname + " " + rt);
    } catch (SQLException e) {
        LOG.error(" get db failed: " + dbname);
        e.printStackTrace();
    }
    return rt;
}

From source file:nu.kelvin.jfileshare.servlets.AboutServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext app = getServletContext();
    RequestDispatcher disp;//from   ww  w  .j  a v  a 2 s.co  m
    req.setAttribute("tab", "About");
    disp = app.getRequestDispatcher("/templates/About.jsp");
    HttpSession session = req.getSession();
    Conf conf = (Conf) app.getAttribute("conf");

    req.setAttribute("daysLogRetention", conf.getDaysLogRetention());

    if (session.getAttribute("user") != null) {
        Connection dbConn = null;
        PreparedStatement st = null;
        try {
            long bytesStoreAvailable = FileSystemUtils.freeSpaceKb(conf.getPathStore()) * 1024;
            req.setAttribute("bytesStoreAvailable", FileItem.humanReadable(bytesStoreAvailable));

            dbConn = ds.getConnection();
            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as logins, cast(count(distinct payload) as char) as uniqueLogins from Logs where action=\"login\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            ResultSet rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("logins", rs.getString("logins"));
                req.setAttribute("uniqueLogins", rs.getString("uniqueLogins"));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as downloads, sum(cast(payload as unsigned)) as bytesDownloads from Logs where action=\"download\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("downloads", rs.getString("downloads"));
                req.setAttribute("bytesDownloads", FileItem.humanReadable(rs.getLong("bytesDownloads")));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as uploads, sum(cast(payload as unsigned)) as bytesUploads from Logs where action=\"upload\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("uploads", rs.getString("uploads"));
                req.setAttribute("bytesUploads", FileItem.humanReadable(rs.getLong("bytesUploads")));
            }
            st.close();
        } catch (SQLException e) {
            logger.severe(e.toString());
        } finally {
            if (dbConn != null) {
                try {
                    dbConn.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }
    disp.forward(req, resp);
}

From source file:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson5a.java

protected AttackResult injectableQuery(String accountName) {
    try {//from   w w  w.  j  a  v a2  s.c om
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";

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

            if ((results != null) && (results.first())) {
                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(success().feedback("sql-injection.5a.success")
                            .feedbackArgs(output.toString()).build());
                } else {
                    return trackProgress(failed().output(output.toString()).build());
                }
            } else {
                return trackProgress(failed().feedback("sql-injection.5a.no.results").build());

            }
        } catch (SQLException sqle) {

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

From source file:org.ensembl.healthcheck.testcase.generic.AnalysisTypes.java

/** 
 * Run the test./*from   w  ww  .  ja  v a 2s .c o  m*/
 * 
 * @param dbre
 *          The database registry containing all the specified databases.
 */
public boolean run(DatabaseRegistryEntry dbre) {

    // only applies to human, mouse and zebrafish at the moment
    Species species = dbre.getSpecies();
    boolean is_merged = isMerged(species);

    if (!is_merged) {

        return true;

    }

    boolean result = true;

    Connection con = dbre.getConnection();

    String[] logicNames = { "ensembl", "havana", "ensembl_havana_gene" };

    // get all chromosomes, ignore LRG and MT
    String[] seqRegionNames = DBUtils.getColumnValues(con,
            "SELECT s.name FROM seq_region s, seq_region_attrib sa, attrib_type at WHERE s.seq_region_id = sa.seq_region_id AND sa.attrib_type_id = at.attrib_type_id AND code = 'karyotype_rank' AND s.name NOT LIKE 'MT'");

    // loop over each seq region, check that each logic name is represented
    try {

        PreparedStatement stmt = con.prepareStatement(
                "SELECT COUNT(*) FROM gene g, seq_region sr, analysis a WHERE a.analysis_id=g.analysis_id AND g.seq_region_id=sr.seq_region_id AND sr.name=? AND a.logic_name=?");

        for (String seqRegion : seqRegionNames) {

            for (String logicName : logicNames) {

                stmt.setString(1, seqRegion);
                stmt.setString(2, logicName);

                ResultSet rs = stmt.executeQuery();

                rs.first();
                int rows = rs.getInt(1);

                if (rows == 0) {

                    result = false;
                    ReportManager.problem(this, con, String
                            .format("Chromosome %s has no genes with logic name %s", seqRegion, logicName));

                }

                rs.close();

            }

        }

        stmt.close();

    } catch (SQLException e) {

        System.err.println("Error executing SQL");
        e.printStackTrace();

    }

    return result;

}

From source file:org.apache.hadoop.hive.ql.metadata.MetaStore.java

public User getUser(Connection cc, String uname) {
    if (cc == null || uname == null) {
        return null;
    }/*from   w  w  w. j a  va  2s  .  com*/
    User rt = null;
    PreparedStatement pstmt;
    try {
        pstmt = cc.prepareStatement(" select USER_ID,GROUP_NAME,PASSWD,USER_NAME,"
                + "ALTER_PRIV,CREATE_PRIV,CREATEVIEW_PRIV,DBA_PRIV,SHOWVIEW_PRIV,"
                + "DELETE_PRIV,DROP_PRIV,INDEX_PRIV,INSERT_PRIV,SELECT_PRIV,UPDATE_PRIV from USER where USER_NAME= ? ");
        pstmt.setString(1, uname);
        ResultSet rs = pstmt.executeQuery();
        rs.first();
        long USER_ID = (long) rs.getLong(1);
        String GROUP_NAME = (String) rs.getObject(2);
        String PASSWD = (String) rs.getObject(3);
        String USER_NAME = (String) rs.getObject(4);
        boolean ALTER_PRIV = (boolean) rs.getBoolean(5);
        boolean CREATE_PRIV = (boolean) rs.getBoolean(6);
        boolean CREATEVIEW_PRIV = (boolean) rs.getBoolean(7);
        boolean DBA_PRIV = (boolean) rs.getBoolean(8);
        boolean SHOWVIEW_PRIV = (boolean) rs.getBoolean(9);
        boolean DELETE_PRIV = (boolean) rs.getBoolean(10);
        boolean DROP_PRIV = (boolean) rs.getBoolean(11);
        boolean INDEX_PRIV = (boolean) rs.getBoolean(12);
        boolean INSERT_PRIV = (boolean) rs.getBoolean(13);
        boolean SELECT_PRIV = (boolean) rs.getBoolean(14);
        boolean UPDATE_PRIV = (boolean) rs.getBoolean(15);
        rt = new User(USER_NAME, null, SELECT_PRIV, INSERT_PRIV, INDEX_PRIV, CREATE_PRIV, DROP_PRIV,
                DELETE_PRIV, ALTER_PRIV, UPDATE_PRIV, CREATEVIEW_PRIV, SHOWVIEW_PRIV, DBA_PRIV, GROUP_NAME);
        rs.close();
        LOG.info(" get user0  : " + rt.toString());
        List<String> playRoles = new LinkedList<String>();
        pstmt = cc.prepareStatement(
                " select ROLE_NAME from PLAY_ROLES join ROLE on PLAY_ROLES.ROLE_ID = ROLE.ROLE_ID where PLAY_ROLES.USER_ID= ? ");
        pstmt.setLong(1, USER_ID);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            String tmpname = (String) rs.getObject(1);
            LOG.info(" ROLE_NAME : " + tmpname);
            playRoles.add(tmpname);
        }
        rs.close();
        rt.setPlayRoles(playRoles);
        LOG.info(" get user1  : " + USER_ID + " " + GROUP_NAME + " " + PASSWD + " " + USER_NAME);
        LOG.info(" get user2  : " + rt.toString());
    } catch (SQLException e) {
        LOG.error(" get user failed: " + uname);
        e.printStackTrace();
    }
    return rt;
}