Example usage for java.sql ResultSet isBeforeFirst

List of usage examples for java.sql ResultSet isBeforeFirst

Introduction

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

Prototype

boolean isBeforeFirst() throws SQLException;

Source Link

Document

Retrieves whether the cursor is before the first row in this ResultSet object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = statement.executeQuery("SELECT * FROM products");

    if (resultSet.isBeforeFirst()) {
        System.out.println("beginning");
    }//from w w  w  . j  a v a  2  s.  c  om
    connection.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = statement.executeQuery("SELECT * FROM products");

    if (resultSet.isBeforeFirst()) {
        System.out.println("isBeforeFirst.");
    }//from   w w w.  j av a 2s .c om
    connection.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);/*  ww w  .ja va  2 s.co m*/

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = stmt.executeQuery("SELECT * FROM my_table");

    // Get cursor position
    int pos = resultSet.getRow();
    boolean b = resultSet.isBeforeFirst();

    // Move cursor to the first row
    resultSet.next();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isFirst();

    // Move cursor to the last row
    resultSet.last();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isLast();

    // Move cursor past last row
    resultSet.afterLast();

    // Get cursor position
    pos = resultSet.getRow();
    b = resultSet.isAfterLast();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    // Get cursor position
    int pos = rs.getRow(); // 0
    System.out.println(pos);/*  ww w.  j a v a  2  s  . c  o  m*/
    boolean b = rs.isBeforeFirst(); // true
    System.out.println(b);

    // Move cursor to the first row
    rs.next();

    // Get cursor position
    pos = rs.getRow(); // 1
    b = rs.isFirst(); // true
    System.out.println(pos);
    System.out.println(b);

    // Move cursor to the last row
    rs.last();
    // Get cursor position
    pos = rs.getRow();
    System.out.println(pos);
    b = rs.isLast(); // true

    // Move cursor past last row
    rs.afterLast();

    // Get cursor position
    pos = rs.getRow();
    b = rs.isAfterLast(); // true

    rs.close();
    st.close();
    conn.close();
}

From source file:ScrollableRs.java

public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
    Connection conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
    Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = stmt.executeQuery("SELECT ssn, name, salary FROM EMPLOYEES");
    while (rs.next()) {
        printRow(rs);/*from   w  ww.j a  v  a 2 s .c o  m*/
    }
    rs.afterLast();
    System.out.println("\"After-last-row\" = " + rs.isAfterLast());
    rs.beforeFirst();
    System.out.println("\"Before-first-row\" = " + rs.isBeforeFirst());
    rs.first();
    printRow(rs);
    rs.last();
    printRow(rs);
    rs.previous();
    printRow(rs);

    rs.next();
    printRow(rs);

    rs.absolute(3);
    printRow(rs);

    rs.relative(-2);
    printRow(rs);
    if (conn != null)
        conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String url = "jdbc:mysql://192.168.100.100:3306/";
    String dbName = "databaseName";
    Statement stmt = null;//from  w  w w .j av a  2s  .c  o  m
    ResultSet result = null;
    String driver = "com.mysql.jdbc.Driver";
    String databaseUserName = "admin";
    String databasePassword = "root";
    Class.forName(driver).newInstance();
    Connection conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
    stmt = conn.createStatement();
    result = null;
    String password, username;
    result = stmt.executeQuery("select * from userTable where username ='user1' ");
    if (!result.isBeforeFirst()) {
        System.out.println("resultset contin no rows");
    }
    while (result.next()) {
        username = result.getString("username");
        password = result.getString("password");
        System.out.println(username + "  " + password);
    }
    conn.close();
}

From source file:at.becast.youploader.account.Account.java

public static boolean exists(String name) {
    Connection c = SQLite.getInstance();
    Statement stmt;/*from   w w w  .ja v  a 2s.com*/
    try {
        stmt = c.createStatement();
        String sql = "SELECT * FROM `accounts` WHERE `name`='" + name + "'";
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.isBeforeFirst()) {
            stmt.close();
            return true;
        } else {
            stmt.close();
            return false;
        }
    } catch (SQLException e) {
        LOG.error("Account exists error!", e);
        return false;
    }
}

From source file:au.org.ala.sds.GeneraliseOccurrenceLocations.java

private static void run(String startAt) throws SQLException, SearchResultException {
    Connection conn = occurrenceDataSource.getConnection();
    PreparedStatement pst = conn.prepareStatement(
            "SELECT id, scientific_name, latitude, longitude, generalised_metres, raw_latitude, raw_longitude FROM raw_occurrence_record LIMIT ?,?");
    int offset = startAt == null ? 0 : Integer.parseInt(startAt);
    int stride = 10000;
    int recCount = 0;
    pst.setInt(2, stride);//from   ww w.  j av a2 s  . c o m
    ResultSet rs;

    for (pst.setInt(1, offset); true; offset += stride, pst.setInt(1, offset)) {
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst()) {
            break;
        }
        while (rs.next()) {
            recCount++;

            String rawScientificName = (rs.getString("scientific_name"));
            int id = rs.getInt("id");
            String latitude = rs.getString("latitude");
            String longitude = rs.getString("longitude");
            String generalised_metres = rs.getString("generalised_metres");
            String raw_latitude = rs.getString("raw_latitude");
            String raw_longitude = rs.getString("raw_longitude");

            if (StringUtils.isEmpty(rawScientificName))
                continue;
            if (StringUtils.isEmpty(latitude) || StringUtils.isEmpty(longitude))
                continue;

            // See if it's sensitive
            SensitiveTaxon ss = sensitiveSpeciesFinder.findSensitiveSpecies(rawScientificName);
            if (ss != null) {
                Map<String, String> facts = new HashMap<String, String>();
                facts.put(FactCollection.DECIMAL_LATITUDE_KEY, latitude);
                facts.put(FactCollection.DECIMAL_LONGITUDE_KEY, longitude);

                ValidationService service = ServiceFactory.createValidationService(ss);
                ValidationOutcome outcome = service.validate(facts);
                Map<String, Object> result = outcome.getResult();

                String speciesName = ss.getTaxonName();
                if (StringUtils.isNotEmpty(ss.getCommonName())) {
                    speciesName += " [" + ss.getCommonName() + "]";
                }

                if (!result.get("decimalLatitude").equals(facts.get("decimalLatitude"))
                        || !result.get("decimalLongitude").equals(facts.get("decimalLongitude"))) {
                    if (StringUtils.isEmpty(generalised_metres)) {
                        logger.info("Generalising location for " + id + " '" + rawScientificName
                                + "' using Name='" + speciesName + "', Lat=" + result.get("decimalLatitude")
                                + ", Long=" + result.get("decimalLongitude"));
                        //rawOccurrenceDao.updateLocation(id, result.get("decimalLatitude"), result.get("decimalLongitude"), result.getGeneralisationInMetres(), latitude, longitude);
                    } else {
                        if (generalised_metres != result.get("generalisationInMetres")) {
                            logger.info("Re-generalising location for " + id + " '" + rawScientificName
                                    + "' using Name='" + speciesName + "', Lat=" + result.get("decimalLatitude")
                                    + ", Long=" + result.get("decimalLongitude"));
                            //rawOccurrenceDao.updateLocation(id, result.get("decimalLatitude"), result.get("decimalLongitude"), result.getGeneralisationInMetres());
                        }
                    }
                } else {
                    logger.info("Not generalising location for " + id + " '" + rawScientificName
                            + "' using Name='" + speciesName + "', Lat=" + result.get("decimalLatitude")
                            + ", Long=" + result.get("decimalLongitude") + " - "
                            + result.get("dataGeneralizations"));
                }
            } else {
                // See if was sensitive but not now
                if (StringUtils.isNotEmpty(generalised_metres)) {
                    logger.info("De-generalising location for " + id + " '" + rawScientificName + "', Lat="
                            + raw_latitude + ", Long=" + raw_longitude);
                    //rawOccurrenceDao.updateLocation(id, raw_latitude, raw_longitude, null, null, null);
                }
            }
        }
        rs.close();
        logger.info("Processed " + recCount + " occurrence records.");
    }

    rs.close();
    pst.close();
    conn.close();
}

From source file:com.wso2telco.dep.validator.handler.utils.ValidatorDBUtils.java

/**
 * Method to retrieve the validator class from the database.
 *
 * @param applicationId/*from w ww  .j  av  a  2 s  .  c  o  m*/
 * @param apiId
 * @return validator class name
 * @throws ValidatorException
 */
public static String getValidatorClassForSubscription(int applicationId, int apiId) throws ValidatorException {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet results = null;
    String sql = "SELECT class FROM validator, subscription_validator "
            + "WHERE subscription_validator.application_id=? AND subscription_validator.api_id=? AND "
            + "validator.id=subscription_validator.validator_id";
    String validatorClass = null;
    try {
        conn = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_DEP_DB);
        ps = conn.prepareStatement(sql);
        log.debug("getValidatorClassForSubscription for applicationId---> " + applicationId + " apiId--> "
                + apiId);
        ps.setInt(1, applicationId);
        ps.setInt(2, apiId);
        results = ps.executeQuery();
        if (results.isBeforeFirst()) {
            while (results.next()) {
                validatorClass = results.getString("class");
            }
        } else {
            log.error("Result Set is empty");
        }
    } catch (Exception e) {
        handleException("Error occured while getting Validator Class for App: " + applicationId + " API: "
                + apiId + " from the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, results);
    }
    return validatorClass;
}

From source file:au.org.paperminer.db.PublisherHelper.java

/**
 * Looks up a record by ID// ww  w  .j  a  va2s  .  c o  m
 * @param id
 * @return Result set for search (you need to close it).
 * @throws PaperMinerException
 */
private HashMap<String, String> getRecord(String id) throws PaperMinerException {
    if (m_data.containsKey(id)) {
        return (HashMap<String, String>) m_data.get(id);
    }

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + PaperMinerConstants.POOL_NAME);
        ps = con.prepareStatement("SELECT * FROM " + TABLE + " WHERE " + ID + " = '" + id + "'");
        ResultSet rs = ps.executeQuery();
        if (rs.isBeforeFirst()) {
            rs.next();
            HashMap<String, String> tmp = new HashMap<String, String>();
            tmp.put(TITLE, rs.getString(TITLE));
            tmp.put(PUB_DATE, rs.getString(PUB_DATE));
            tmp.put(LAT, rs.getString(LAT));
            tmp.put(LONG, rs.getString(LONG));
            tmp.put(LOCN, rs.getString(LOCN));
            m_data.put(id, tmp);
            rs.close();
            m_logger.debug("Got lat/long for id=" + id + " (" + tmp.get(TITLE) + ")");
            return tmp;
        }
    } catch (SQLException ex) {
        m_logger.error("Error fetching lat/long for id=" + id, ex);
        throw new PaperMinerException("Fetch update failed, see log");
    } finally {
        if (con != null) {
            try {
                con.close();
                if (ps != null) {
                    ps.close();
                }
            } catch (SQLException ex) {
                m_logger.warn("SQL error during cleanup", ex);
            }
        }
    }
    return null;
}