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:net.mms_projects.copy_it.api.http.pages.v1.ClipboardGet.java

public FullHttpResponse onGetRequest(HttpRequest request, Database database, HeaderVerifier headerVerifier)
        throws Exception {
    if (!headerVerifier.getConsumerScope().canRead() || !headerVerifier.getUserScope().canRead())
        throw new ErrorException(NO_READ_PERMISSION);
    PreparedStatement statement = database.getConnection().prepareStatement(SELECT_CONTENT);
    statement.setInt(1, headerVerifier.getUserId());
    ResultSet result = statement.executeQuery();
    if (result.first()) {
        final JSONObject json = new JSONObject();
        json.put(CONTENT, result.getString(DATA));
        json.put(LAST_UPDATED, result.getInt(LAST_UPDATED));
        result.close();//from  w  w  w .ja  v  a  2  s. co m
        return new DefaultFullHttpResponse(request.getProtocolVersion(), OK,
                Unpooled.copiedBuffer(json.toString(), CharsetUtil.UTF_8));
    }
    result.close();
    throw new NoContentException();
}

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

@Override
public PhoneModel getPhoneInfo(String name) {
    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 {// w w w .  j  a v a 2  s  .  co  m
        connection = datasource.getConnection();
        String sql = "SELECT id, name, brand, opsys, displaySize " + "FROM telefono WHERE name = ? ;";
        PreparedStatement stat = connection.prepareStatement(sql);
        stat.setString(1, name);
        ResultSet res = stat.executeQuery();
        if (res.first()) {
            phone.setNome(res.getString("name"));
            phone.setBrand(res.getString("brand"));
            phone.setOpsys(res.getString("opsys"));
            phone.setDisplay(res.getString("displaySize"));
        } else {
            phone = null;
        }
    } catch (SQLException e) {
        logger.error(e);
        phone = null;
    } finally {
        DbUtils.closeQuietly(connection);
    }
    return phone;
}

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

public void dispatchNotification(Database database, int user_id) throws SQLException {
    PreparedStatement statement = database.getConnection().prepareStatement(SELECT_GCM_TOKENS);
    statement.setInt(1, user_id);// w  ww .  jav a2s .c o m
    ResultSet resultSet = statement.executeQuery();
    if (resultSet.first()) {
        GCMRunnable gcm = new GCMRunnable();
        do {
            gcm.addRegistrationId(resultSet.getString(GCM_TOKEN));
        } while (resultSet.next());
        gcm.setData("action", "content-updated");
        postProcess(gcm);
    }
    resultSet.close();
}

From source file:com.bstek.dorado.core.store.H2BaseStore.java

protected void prepareNamespace() throws Exception {
    Class.forName(driverClassName);
    Connection conn = DriverManager.getConnection(getConnectionUrl(), username, password);
    try {//from   w  w  w . ja va  2s  . co m
        int storeVersion = 0;
        CallableStatement prepareCall = conn.prepareCall("SELECT @storeVersion");
        ResultSet resultSet = prepareCall.executeQuery();
        try {
            if (resultSet.first()) {
                storeVersion = resultSet.getInt("@storeVersion");
            }
        } finally {
            resultSet.close();
            prepareCall.close();
        }

        if (storeVersion < version) {
            logger.info("Initializing store \"" + namespace + "\".");

            prepareCall = conn.prepareCall("SET @storeVersion = " + version);
            try {
                prepareCall.execute();
            } finally {
                prepareCall.close();
            }

            initNamespace(conn);
        }
    } finally {
        conn.close();
    }
}

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

protected String getPassword() {

    String password = "dave";
    try {//from  ww  w  .  j a v  a  2s  .  c  o m
        Connection connection = DatabaseUtilities.getConnection(getWebSession());
        String query = "SELECT password FROM user_system_data WHERE user_name = 'dave'";

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

            if ((results != null) && (results.first() == true)) {
                password = results.getString("password");
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            // do nothing
        }
    } catch (Exception e) {
        e.printStackTrace();
        // do nothing
    }
    return (password);
}

From source file:com.chiorichan.database.DatabaseEngine.java

public static LinkedHashMap<String, Object> convert(ResultSet rs) throws SQLException, JSONException {
    LinkedHashMap<String, Object> result = new LinkedHashMap<String, Object>();
    int x = 0;/*from   w  w  w  . j a v  a 2  s  .co m*/

    rs.first();

    do {
        result.put("" + x, convertRow(rs));
        x++;
    } while (rs.next());

    return result;
}

From source file:org.ensembl.healthcheck.testcase.compara.Meta.java

/**
 * Check that the schema_version in the meta table is present and matches the database name.
 *//*from   w  ww . jav  a 2  s . c o m*/
private boolean checkSchemaVersionDBName(DatabaseRegistryEntry dbre) {

    boolean result = true;

    // get version from database name
    String dbNameVersion = dbre.getSchemaVersion();

    logger.finest("Schema version from database name: " + dbNameVersion);

    // get version from meta table
    Connection con = dbre.getConnection();

    // Get current global value from the meta table (used for backwards compatibility)
    String sql = "SELECT meta_key, meta_value" + " FROM meta WHERE meta_key = \"schema_version\"";
    try {
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.first()) {
            if (rs.getInt(2) != new Integer(dbNameVersion).intValue()) {
                EntriesToUpdate.put("schema_version", dbNameVersion);
            }
        } else {
            EntriesToAdd.put("schema_version", dbNameVersion);
        }
        rs.close();
        stmt.close();
    } catch (SQLException se) {
        se.printStackTrace();
        result = false;
    }

    return result;

}

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

public SmartphoneModel getSmartphoneInfo(String imei) {

    SmartphoneModel smartphoneModel = new SmartphoneModel();

    MysqlDataSource dataSource = new MysqlDataSource();

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

    Connection conn = null;/* w w w.  j a va2 s  . com*/

    try {

        conn = dataSource.getConnection();

        PreparedStatement stmtUserInfo = conn.prepareStatement(SMARTPHONE_INFO);

        stmtUserInfo.setString(1, imei);

        ResultSet rsUserInfoSet = stmtUserInfo.executeQuery();

        if (rsUserInfoSet.first()) {

            smartphoneModel = new SmartphoneModel();
            smartphoneModel.setMarca(rsUserInfoSet.getString("marca"));
            smartphoneModel.setModello(rsUserInfoSet.getString("modello"));
            smartphoneModel.setColore(rsUserInfoSet.getString("colore"));
            smartphoneModel.setMateriale(rsUserInfoSet.getString("materiale"));

        }

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

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

    return smartphoneModel;
}

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

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

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

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

            }
        } 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:com.linkedin.pinot.integration.tests.RealtimeClusterIntegrationTest.java

@BeforeClass
public void setUp() throws Exception {
    // Start ZK and Kafka
    startZk();/*from  w  ww .j ava2 s . c om*/
    kafkaStarters = KafkaStarterUtils.startServers(getKafkaBrokerCount(), KafkaStarterUtils.DEFAULT_KAFKA_PORT,
            KafkaStarterUtils.DEFAULT_ZK_STR, KafkaStarterUtils.getDefaultKafkaConfiguration());

    // Create Kafka topic
    createKafkaTopic(KAFKA_TOPIC, KafkaStarterUtils.DEFAULT_ZK_STR);

    // Start the Pinot cluster
    startController();
    startBroker();
    startServer();

    // Unpack data
    final List<File> avroFiles = unpackAvroData(_tmpDir, SEGMENT_COUNT);

    File schemaFile = getSchemaFile();

    // Load data into H2
    ExecutorService executor = Executors.newCachedThreadPool();
    setupH2AndInsertAvro(avroFiles, executor);

    // Initialize query generator
    setupQueryGenerator(avroFiles, executor);

    // Push data into the Kafka topic
    pushAvroIntoKafka(avroFiles, executor, KAFKA_TOPIC);

    // Wait for data push, query generator initialization and H2 load to complete
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MINUTES);

    // Create Pinot table
    setUpTable("mytable", "DaysSinceEpoch", "daysSinceEpoch", KafkaStarterUtils.DEFAULT_ZK_STR, KAFKA_TOPIC,
            schemaFile, avroFiles.get(0));

    // Wait until the Pinot event count matches with the number of events in the Avro files
    long timeInFiveMinutes = System.currentTimeMillis() + 5 * 60 * 1000L;
    Statement statement = _connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    statement.execute("select count(*) from mytable");
    ResultSet rs = statement.getResultSet();
    rs.first();
    int h2RecordCount = rs.getInt(1);
    rs.close();

    waitForRecordCountToStabilizeToExpectedCount(h2RecordCount, timeInFiveMinutes);
}