Example usage for java.sql ResultSet TYPE_SCROLL_INSENSITIVE

List of usage examples for java.sql ResultSet TYPE_SCROLL_INSENSITIVE

Introduction

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

Prototype

int TYPE_SCROLL_INSENSITIVE

To view the source code for java.sql ResultSet TYPE_SCROLL_INSENSITIVE.

Click Source Link

Document

The constant indicating the type for a ResultSet object that is scrollable but generally not sensitive to changes to the data that underlies the ResultSet.

Usage

From source file:org.exolab.castor.jdo.engine.SQLQuery.java

public void execute(final CastorConnection conn, final AccessMode accessMode, final boolean scrollable)
        throws PersistenceException {
    // create SQL statement from _sql, replacing bind expressions like "?1" by "?"
    String sql = SqlBindParser.getJdbcSql(_sql);

    _lastIdentity = null;//from   w w w  . j a v a 2s . c  o  m

    try {
        if (scrollable) {
            _stmt = conn.getConnection().prepareStatement(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,
                    java.sql.ResultSet.CONCUR_READ_ONLY);
        } else {
            _stmt = conn.getConnection().prepareStatement(sql);
        }

        // bind variable values on _values to the JDBC statement _stmt using the bind
        // variable order in _sql 
        SqlBindParser.bindJdbcValues(_stmt, _sql, _values);

        // erase bind values
        for (int i = 0; i < _values.length; ++i) {
            _values[i] = null;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(Messages.format("jdo.executingSql", sql));
        }

        _rs = _stmt.executeQuery();
        _resultSetDone = false;
    } catch (SQLException except) {
        if (_stmt != null) {
            try {
                _stmt.close();
            } catch (SQLException e2) {
                LOG.warn("Problem closing JDBC statement", e2);
            }
        }
        _resultSetDone = true;
        throw new PersistenceException(Messages.format("persist.nested", except) + " while executing " + _sql,
                except);
    }
}

From source file:com.norconex.collector.http.db.impl.derby.DerbyCrawlURLDatabase.java

@Override
public Iterator<CrawlURL> getCacheIterator() {
    try {/*from  www.  j a v a  2 s.c  o  m*/
        final Connection conn = datasource.getConnection();
        final Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        final ResultSet rs = stmt.executeQuery(
                "SELECT url, depth, smLastMod, smChangeFreq, smPriority " + "FROM " + TABLE_CACHE);
        if (rs == null || !rs.first()) {
            return null;
        }
        rs.beforeFirst();
        return new CrawlURLIterator(rs, conn, stmt);
    } catch (SQLException e) {
        throw new CrawlURLDatabaseException("Problem getting database cache iterator.", e);
    }
}

From source file:fr.gael.dhus.server.http.webapp.symmetricDS.SymmetricDSWebapp.java

@Override
public void checkInstallation() throws Exception {
    if (!scalabilityManager.isMaster())
        return;//from   w ww.  ja  v a 2s. co  m

    // Check database is ready for SymmetricDS
    PreparedStatement ps = datasource.getConnection().prepareStatement(
            "SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME='SYM_FK_TRGPLT_2_TR';",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

    while (!ps.executeQuery().first()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    ps.close();
    // Check if init.sql has already been executed
    ps = datasource.getConnection().prepareStatement(
            "SELECT node_group_id FROM SYM_NODE_GROUP WHERE node_group_id = 'dhus-replica-group';",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

    if (!ps.executeQuery().first()) {
        // Wait for master group to be inserted         
        PreparedStatement ps2 = datasource.getConnection().prepareStatement(
                "SELECT * FROM SYM_NODE_GROUP WHERE node_group_id='dhus-master-group';",
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        while (!ps2.executeQuery().first()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        ps2.close();

        ScriptUtils.executeSqlScript(datasource.getConnection(),
                new ClassPathResource("fr/gael/dhus/server/http/webapp/symmetricDS/init.sql"));
        LOGGER.info("SymmetricDS initialization script loaded");

        // Force the synchronizers to be reloaded
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(
                cfgManager.getServerConfiguration().getLocalUrl() + "/sync/api/engine/synctriggers");

        httpclient.execute(httppost);
    }
    ps.close();
}

From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java

public Map<String, String> getSurveyIdToUrlMap() {
    Map<String, String> surveyIdsToUrlMap = new HashMap<String, String>();
    PreparedStatement listSurveysStmt = null;
    Connection conn = null;/*  www .  ja v  a  2  s .  c  o m*/
    try {
        conn = getDbConnection();
        listSurveysStmt = conn.prepareStatement(SELECT_ALL_SURVEYS_STATEMENT, ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        ResultSet surveysSet = listSurveysStmt.executeQuery();
        boolean isValidRow = surveysSet.first();
        final String FAKE_DEVICE_ID = "0";
        while (isValidRow) {
            String surveyId = surveysSet.getString(SURVEY_ID_COLUMN);
            surveyIdsToUrlMap.put(surveyId, getSurveyDownloadUrl(FAKE_DEVICE_ID, surveyId));
            isValidRow = surveysSet.next();
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            listSurveysStmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
    return surveyIdsToUrlMap;
}

From source file:recite18th.library.Db.java

public static String[][] getDataSet(String sqlStatement) {
    try {/*from  w  w  w. j  ava 2s.c  o  m*/
        Statement stmt = getCon().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        Logger.getLogger(Db.class.getName()).log(Level.INFO, "getDataSet:" + sqlStatement);
        return processDataSetResultSet(stmt.executeQuery(sqlStatement));

    } catch (SQLException ex) {
        Logger.getLogger(Db.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

}

From source file:IDlook.java

public void connectToDB() {
    try {//  w w w.j av  a 2 s .com
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/identification?user=spider&password=spider");
        statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

    } catch (SQLException connectException) {
        System.out.println(connectException.getMessage());
        System.out.println(connectException.getSQLState());
        System.out.println(connectException.getErrorCode());
        System.exit(1);
    }
}

From source file:skyline.platform.db.DatabaseConnection.java

/**
 * Description of the Method/*from w w  w .j av  a 2 s .  c  o m*/
 * 
 * @param sql
 *          Description of the Parameter
 * @param beginIndex
 *          Description of the Parameter
 * @param resultNo
 *          Description of the Parameter
 * @return Description of the Return Value
 */
public RecordSet executeQuery(String sql, int beginIndex, int resultNo) {
    if (sql == null || sql.trim().length() == 0) {
        logger.error("DatabaseConnection.executeQuery's sql parameter is null!!!");
        return new RecordSet();
    }
    //sql
    printsql(sql);

    try {
        String pageSql = "";
        Statement st = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        if (Basic.getDbType().equals("DB2")) {
            pageSql = " select * from (SELECT ta.*, ROWNUMBER() OVER ()  rn FROM ( " + sql + ") ta FETCH FIRST "
                    + (beginIndex - 1 + resultNo) + " ROW ONLY) tb where tb.rn>" + (beginIndex - 1);
        } else
            pageSql = " select * from ( select t1.*, rownum rnum from ( " + sql + " ) t1 where rownum<= "
                    + (beginIndex - 1 + resultNo) + " ) t2 where t2.rnum> " + (beginIndex - 1);
        // sql
        printsql("page sql:" + pageSql);
        ResultSet rs = st.executeQuery(pageSql);
        RecordSet records = new RecordSet(rs);

        rs.close();
        st.close();
        return records;
    } catch (SQLException sqle) {
        errorException = sqle;
        logger.error("", sqle);
        return new RecordSet();
    }
}

From source file:com.itemanalysis.jmetrik.stats.ranking.RankingAnalysis.java

public String compute() throws SQLException {
    Statement stmt = null;//  w ww .  j a v a2 s  .  c  om
    ResultSet rs = null;

    try {
        //get data
        ResizableDoubleArray data = getData();

        //create columns - dao uses its own transaction
        int numberOfColumns = dao.getColumnCount(conn, tableName);
        int columnNumber = numberOfColumns + 1;
        String newVariableLabel = "Rank";
        if (blom)
            newVariableLabel = "Blom Normal Score";
        if (tukey)
            newVariableLabel = "Tukey Normal Score";
        if (vdw)
            newVariableLabel = "van der Waerden Normal Score";
        if (ntiles)
            newVariableLabel = "Quantiles: " + numGroups + " groups";
        newVariable = new VariableAttributes(newVariableName, newVariableLabel, ItemType.NOT_ITEM,
                DataType.DOUBLE, columnNumber++, "");

        dao.addColumnToDb(conn, tableName, newVariable);

        //compute ranks
        NaturalRanking ranking = new NaturalRanking(NaNStrategy.REMOVED, tiesStrategy);
        double[] ranks = ranking.rank(data.getElements());

        //begin transaction
        conn.setAutoCommit(false);

        //connect to table and update values
        SelectQuery select = new SelectQuery();
        Table sqlTable = new Table(tableName.getNameForDatabase());
        select.addColumn(sqlTable, newVariable.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(select.toString());

        int nRanks = ranks.length;
        int rankIndex = 0;//array index for ranks (missing values not included)
        int dbIndex = 0;//db row position for case (missing values included)
        double r = Double.NaN;
        boolean missing = false;
        String tempName = "";
        while (rs.next()) {
            missing = missingIndex.contains(dbIndex);
            if (missing) {
                rs.updateNull(newVariable.getName().nameForDatabase());
            } else {
                r = ranks[rankIndex];
                if (blom) {
                    rs.updateDouble(newVariable.getName().nameForDatabase(),
                            normScore.blom(r, (double) nRanks));
                } else if (tukey) {
                    rs.updateDouble(newVariable.getName().nameForDatabase(),
                            normScore.tukey(r, (double) nRanks));
                } else if (vdw) {
                    rs.updateDouble(newVariable.getName().nameForDatabase(),
                            normScore.vanderWaerden(r, (double) nRanks));
                } else if (ntiles) {
                    rs.updateDouble(newVariable.getName().nameForDatabase(),
                            getGroup(r, (double) nRanks, (double) numGroups));
                } else {
                    rs.updateDouble(newVariable.getName().nameForDatabase(), r);
                }
                rankIndex++;
            }
            rs.updateRow();
            updateProgress();
            dbIndex++;
        }
        conn.commit();
        return "Ranks computed";
    } catch (SQLException ex) {
        conn.rollback();
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
        conn.setAutoCommit(true);
    }

}

From source file:no.polaric.aprsdb.MyDBSession.java

public DbList<Sign.Category> getCategories() throws java.sql.SQLException {
    PreparedStatement stmt = getCon().prepareStatement(" SELECT * from \"SignClass\" ORDER BY name ASC ",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

    return new DbList(stmt.executeQuery(), rs -> {
        return new Sign.Category(rs.getInt("id"), rs.getString("name"), rs.getString("icon"));
    });/* w  w  w  .  j ava2 s . c  om*/
}

From source file:net.starschema.clouddb.jdbc.BQStatementRoot.java

/** {@inheritDoc} */

public ResultSet executeQuery(String querySql) throws SQLException {
    if (this.isClosed()) {
        throw new BQSQLException("This Statement is Closed");
    }/*  w w  w .  j a va  2  s . c om*/
    this.starttime = System.currentTimeMillis();
    Job referencedJob;
    // ANTLR Parsing
    BQQueryParser parser = new BQQueryParser(querySql, this.connection);
    querySql = parser.parse();

    try {
        // Gets the Job reference of the completed job with give Query
        referencedJob = BQSupportFuncts.startQuery(this.connection.getBigquery(), this.ProjectId, querySql);
        this.logger.info("Executing Query: " + querySql);
    } catch (IOException e) {
        throw new BQSQLException("Something went wrong with the query: " + querySql, e);
    }
    try {
        do {
            if (BQSupportFuncts.getQueryState(referencedJob, this.connection.getBigquery(), this.ProjectId)
                    .equals("DONE")) {
                if (resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE) {
                    return new BQScrollableResultSet(BQSupportFuncts.getQueryResults(
                            this.connection.getBigquery(), this.ProjectId, referencedJob), this);
                } else {
                    return new BQForwardOnlyResultSet(this.connection.getBigquery(),
                            this.ProjectId.replace("__", ":").replace("_", "."), referencedJob, this);
                }
            }
            // Pause execution for half second before polling job status
            // again, to
            // reduce unnecessary calls to the BigQUery API and lower
            // overall
            // application bandwidth.
            Thread.sleep(500);
            this.logger.debug("slept for 500" + "ms, querytimeout is: " + this.querytimeout + "s");
        } while (System.currentTimeMillis() - this.starttime <= (long) this.querytimeout * 1000);
        // it runs for a minimum of 1 time
    } catch (IOException e) {
        throw new BQSQLException("Something went wrong with the query: " + querySql, e);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    // here we should kill/stop the running job, but bigquery doesn't
    // support that :(
    throw new BQSQLException("Query run took more than the specified timeout");
}