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:main.export.sql.DocBuilder.java

@SuppressWarnings("unchecked")
public Map<String, Object> getFields(Map<String, Object> firstRow, ResultSet rs, Entity entity,
        Map<String, Object> entityMap, Map<String, Object> rootEntityMap) throws SQLException {

    entityMap = new HashMap<String, Object>();

    if (entity.allAttributes.get(MULTI_VALUED) != null
            && entity.allAttributes.get(MULTI_VALUED).equalsIgnoreCase("true")) {
        List<Object> fieldArray = new ArrayList<Object>();
        rs.beforeFirst();/*from  w ww.  ja v a2 s  .  c o  m*/
        while (rs.next()) {
            if (entity.fields.size() > 1) {
                Map<String, Object> entityFieldsMap = new HashMap<String, Object>();
                for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) {
                    Field field = (Field) iterator.next();
                    FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase());
                    entityFieldsMap.put(field.name,
                            convertFieldType(fieldType, rs.getObject(field.column)).get(0));
                }
                fieldArray.add(entityFieldsMap);
            } else if (entity.fields.size() == 1) {
                fieldArray.add(rs.getObject(entity.fields.get(0).column));
            }
        }
        rootEntityMap.put(entity.name, fieldArray);
    } else if (firstRow != null) {
        for (Iterator<Field> iterator = entity.fields.iterator(); iterator.hasNext();) {
            Field field = (Field) iterator.next();
            FieldType fieldType = FieldType.valueOf(field.allAttributes.get("type").toUpperCase());

            if (firstRow.get(field.column) != null) {
                if (entity.pk != null && entity.pk.equals(field.name)) {
                    if (importer.getDataStoreType().equals(DataStoreType.MONGO)) {
                        entityMap.put("_id", convertFieldType(fieldType, firstRow.get(field.column)).get(0));
                    } else if (importer.getDataStoreType().equals(DataStoreType.COUCH)) {
                        // couch db says document id must be string
                        entityMap.put("_id",
                                convertFieldType(FieldType.STRING, firstRow.get(field.column)).get(0));
                    }
                } else {
                    entityMap.put(field.getName(),
                            convertFieldType(fieldType, firstRow.get(field.column)).get(0));
                }

                params.put(entity.name + "." + field.name, firstRow.get(field.column).toString());
            }

        }
    }

    if (entity.entities != null) {
        Entity subEntity = null;
        String query = "", aparam = "";
        for (Iterator<Entity> iterator = entity.entities.iterator(); iterator.hasNext();) {
            subEntity = (Entity) iterator.next();
            subLevel = subConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            query = subEntity.allAttributes.get("query");

            m = p.matcher(query);
            aparam = "";
            try {
                log.info("Parameter Map is: " + params);
                while (m.find()) {
                    aparam = query.substring(m.start() + 2, m.end() - 1);
                    query = query.replaceAll("(\\$\\{" + aparam + "\\})",
                            Matcher.quoteReplacement(StringEscapeUtils.escapeSql(params.get(aparam))));
                    m = p.matcher(query);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            resultSet = subLevel.executeQuery(query);
            if (resultSet.next()) {
                subEntityData = getFields(processor.toMap(resultSet), resultSet, subEntity, null, entityMap);
                if (subEntityData.size() > 0)
                    entityMap.put(subEntity.name, subEntityData);
            }
            resultSet.close();
            subLevel.close();
        }
    }
    return entityMap;
}

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

/**
 * Get trail for a given station and a given time span. 
 */// w  w  w . j  av  a2s  . c om
public DbList<TPoint> getTrail(String src, java.util.Date from, java.util.Date to, boolean rev)
        throws java.sql.SQLException {
    _log.debug("MyDbSession", "getTrail: " + src + ", " + df.format(from) + " - " + df.format(to));
    PreparedStatement stmt = getCon().prepareStatement(
            " SELECT * FROM \"PosReport\"" + " WHERE src=? AND time >= ? AND time <= ?" + " ORDER BY time "
                    + (rev ? "DESC" : "ASC") + " LIMIT 500",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    stmt.setString(1, src);
    stmt.setTimestamp(2, date2ts(from));
    stmt.setTimestamp(3, date2ts(to));
    stmt.setMaxRows(500);

    return new DbList(stmt.executeQuery(), rs -> {
        return new TPoint(rs.getTimestamp("time"), getRef(rs, "position"));
    });
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

public void testAbsolute() throws SQLException {
    stat = conn.createStatement();//  w w  w  .j  a v a  2  s.c  o  m
    stat.execute("CREATE TABLE test(ID INT PRIMARY KEY)");
    // there was a problem when more than MAX_MEMORY_ROWS where in the result
    // set
    stat.execute("INSERT INTO test SELECT X FROM SYSTEM_RANGE(1, 200)");
    Statement s2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = s2.executeQuery("SELECT * FROM test ORDER BY ID");
    for (int i = 100; i > 0; i--) {
        rs.absolute(i);
        assertEquals(i, rs.getInt(1));
    }
    stat.execute("DROP TABLE test");
}

From source file:com.sun.faces.mock.MockResultSet.java

public int getType() throws SQLException {

    return (ResultSet.TYPE_SCROLL_INSENSITIVE);

}

From source file:io.cloudslang.content.database.utils.SQLInputsUtils.java

@NotNull
private static Map<String, Integer> createTypeValues() {
    final Map<String, Integer> typeValues = new HashMap<>();
    typeValues.put(TYPE_FORWARD_ONLY, ResultSet.TYPE_FORWARD_ONLY);
    typeValues.put(TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE);
    typeValues.put(TYPE_SCROLL_SENSITIVE, ResultSet.TYPE_SCROLL_SENSITIVE);
    return typeValues;
}

From source file:com.tera.common.database.query.CQueryService.java

@Override
public int[] getUsedIds(String query, String idColumn) {
    PreparedStatement statement = prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ResultSet resultSet = null;//from   w w  w  . j  a va 2s . co  m
    try {
        resultSet = statement.executeQuery();
        resultSet.last();
        int count = resultSet.getRow();
        resultSet.beforeFirst();
        int[] ids = new int[count];
        for (int i = 0; i < count; i++) {
            resultSet.next();
            ids[i] = resultSet.getInt(idColumn);
        }
        return ids;
    } catch (SQLException e) {
        log.error("Can't get id's using query {}", query, e);
    } finally {
        close(resultSet, statement);
    }

    return new int[0];
}

From source file:edu.ku.brc.specify.conversion.IdHashMapper.java

/**
 * Maps the first index to the second index.
 * The SQL to do the mappings./*  www  . j av  a  2 s . c o m*/
 */
public void mapAllIds() {
    if (sql == null) {
        throw new RuntimeException("Calling mapAllIds and the SQL statement is NULL!");
    }

    int mappingCount = getMapCount(mapTableName);
    wasEmpty = mappingCount == 0;

    if (doDelete || mappingCount == 0) {
        if (!isUsingSQL) {
            BasicSQLUtils.deleteAllRecordsFromTable(oldConn, mapTableName,
                    BasicSQLUtils.myDestinationServerType);
        }

        if (frame != null) {
            frame.setDesc("Mapping " + mapTableName);
        }

        try {
            if (frame != null) {
                frame.setProcess(0, 0);
            }

            PreparedStatement pStmt = oldConn.prepareStatement("INSERT INTO " + mapTableName + " VALUES (?,?)");
            Statement stmtOld = oldConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            ResultSet rs = stmtOld.executeQuery(sql);
            if (rs.last()) {
                if (frame != null) {
                    frame.setProcess(0, rs.getRow());
                }
            }

            if (rs.first()) {
                int count = 0;
                do {
                    pStmt.setInt(1, rs.getInt(1)); // Old Index
                    pStmt.setInt(2, rs.getInt(2)); // New Index
                    if (pStmt.executeUpdate() != 1) {
                        String msg = String.format("Error writing to Map table[%s] old: %d  new: %d",
                                mapTableName, rs.getInt(1), rs.getInt(2));
                        log.error(msg);
                        throw new RuntimeException(msg);
                    }

                    if (frame != null) {
                        if (count % 1000 == 0) {
                            frame.setProcess(count);
                        }

                    } else {
                        if (count % 2000 == 0) {
                            log.debug("Mapped " + count + " records from " + tableName);
                        }
                    }
                    count++;

                } while (rs.next());

                log.info("Mapped " + count + " records from " + tableName);
                if (frame != null) {
                    frame.setProcess(0, 0);
                }

            } else {
                log.info("No records to map in " + tableName);
            }
            rs.close();

            stmtOld.close();
            pStmt.close();

        } catch (SQLException ex) {
            ex.printStackTrace();
            edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(IdHashMapper.class, ex);
            log.error("trying to execute:" + sql);
            log.error(ex);

            throw new RuntimeException(ex);
        }
    } else {
        log.debug("Skipping the build of mapper: " + mapTableName);
    }

    if (frame != null) {
        frame.setProcess(0, 0);
    }

}

From source file:org.jumpmind.vaadin.ui.sqlexplorer.SqlRunner.java

@Override
public void run() {
    TypedProperties properties = settings.getProperties();
    boolean resultsAsText = properties.is(SQL_EXPLORER_RESULT_AS_TEXT);
    int maxResultsSize = properties.getInt(SQL_EXPLORER_MAX_RESULTS);
    String delimiter = properties.get(SQL_EXPLORER_DELIMITER);
    boolean ignoreWhenRunAsScript = properties.is(SQL_EXPLORER_IGNORE_ERRORS_WHEN_RUNNING_SCRIPTS);

    List<Component> resultComponents = new ArrayList<Component>();
    FontAwesome icon = FontAwesome.CHECK_CIRCLE;
    rowsUpdated = false;//from w  w w.  ja v a2 s  .c o  m
    boolean committed = false;
    boolean autoCommitBefore = true;
    try {
        DataSource dataSource = db.getPlatform().getDataSource();
        JdbcSqlTemplate sqlTemplate = (JdbcSqlTemplate) db.getPlatform().getSqlTemplate();
        stmt = null;
        StringBuilder results = new StringBuilder();
        try {
            if (connection == null) {
                connection = dataSource.getConnection();
                connection.setAutoCommit(autoCommit);
            }

            autoCommitBefore = connection.getAutoCommit();
            if (connection.getTransactionIsolation() != sqlTemplate.getIsolationLevel()) {
                connection.setTransactionIsolation(sqlTemplate.getIsolationLevel());
            }
            if (sqlTemplate.isRequiresAutoCommitFalseToSetFetchSize()) {
                connection.setAutoCommit(false);
            }

            SqlScriptReader sqlReader = null;
            try {
                sqlReader = new SqlScriptReader(new StringReader(sqlText));
                sqlReader.setDelimiter(delimiter);
                String sql = sqlReader.readSqlStatement();
                while (sql != null) {
                    JdbcSqlTemplate.close(stmt);
                    if (db.getPlatform().getName().equals("voltdb")) {
                        stmt = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                                ResultSet.CONCUR_READ_ONLY);
                    } else {
                        stmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY,
                                ResultSet.CONCUR_READ_ONLY);
                    }

                    String lowercaseSql = sql.trim().toLowerCase();
                    if (!lowercaseSql.startsWith("delete") && !lowercaseSql.startsWith("update")
                            && !lowercaseSql.startsWith("insert")) {
                        if (db.getPlatform().getName().equals(DatabaseNamesConstants.MYSQL)) {
                            stmt.setFetchSize(Integer.MIN_VALUE);
                        } else {
                            stmt.setFetchSize(maxResultsSize < 100 ? maxResultsSize : 100);
                        }
                    }

                    if (logAtDebug) {
                        log.debug("[" + db.getName() + "] Executing: {}", sql.trim());

                    } else {
                        log.info("[" + db.getName() + "] Executing: {}", sql.trim());
                    }
                    if (sql.replaceAll("\\s", "").equalsIgnoreCase(COMMIT_COMMAND)) {
                        committed = true;
                    } else {
                        committed = false;
                    }

                    boolean hasResults = false;
                    try {
                        hasResults = stmt.execute();
                    } catch (SQLException e) {
                        if (runAsScript && ignoreWhenRunAsScript) {
                            results.append(sql);
                            results.append("\n");
                            results.append(buildErrorMessage(e));
                            results.append("\n");
                            results.append("\n");
                        } else {
                            throw e;
                        }
                    }
                    int updateCount = stmt.getUpdateCount();
                    while (hasResults || updateCount != -1) {
                        ResultSet rs = null;
                        try {
                            if (hasResults) {
                                rs = stmt.getResultSet();
                                if (!runAsScript) {
                                    if (!resultsAsText) {
                                        resultComponents.add(new TabularResultLayout(explorer, db, sql, rs,
                                                listener, user, settings, queryPanel, showSqlOnResults,
                                                isInQueryGeneralResults));
                                    } else {
                                        resultComponents.add(putResultsInArea(stmt, maxResultsSize));
                                    }
                                } else {
                                    int rowsRetrieved = 0;
                                    while (rs.next()) {
                                        rowsRetrieved++;
                                    }
                                    results.append(sql);
                                    results.append("\n");
                                    results.append("Rows Retrieved: ");
                                    results.append(rowsRetrieved);
                                    results.append("\n");
                                    results.append("\n");
                                }
                            } else {
                                rowsUpdated = updateCount > 0 ? true : false;
                                if (!runAsScript) {
                                    resultComponents.add(wrapTextInComponent(
                                            String.format("%d rows affected", updateCount)));
                                } else {
                                    results.append(sql);
                                    results.append("\n");
                                    results.append("Rows Affected: ");
                                    results.append(updateCount);
                                    results.append("\n");
                                    results.append("\n");
                                }
                            }
                            hasResults = stmt.getMoreResults();
                            updateCount = stmt.getUpdateCount();
                        } finally {
                            JdbcSqlTemplate.close(rs);
                        }
                    }

                    sql = sqlReader.readSqlStatement();

                }

            } finally {
                IOUtils.closeQuietly(sqlReader);
            }

        } catch (Throwable ex) {
            if (isCanceled) {
                String canceledMessage = "Canceled successfully.\n\n" + sqlText;
                resultComponents.add(wrapTextInComponent(canceledMessage));
            } else {
                icon = FontAwesome.BAN;
                resultComponents.add(wrapTextInComponent(buildErrorMessage(ex), "marked"));
            }
        } finally {
            if (autoCommitBefore) {
                try {
                    connection.commit();
                    connection.setAutoCommit(autoCommitBefore);
                } catch (SQLException e) {
                }
            }
            JdbcSqlTemplate.close(stmt);
            if (autoCommit || (!autoCommit && !rowsUpdated && createdConnection)) {
                JdbcSqlTemplate.close(connection);
                connection = null;
            }

        }

        if (resultComponents.size() == 0 && StringUtils.isNotBlank(results.toString())) {
            resultComponents
                    .add(wrapTextInComponent(results.toString(), icon == FontAwesome.BAN ? "marked" : null));
        }

    } finally {
        endTime = new Date();
        if (listener != null) {
            listener.finished(icon, resultComponents, endTime.getTime() - startTime.getTime(),
                    !autoCommit && rowsUpdated, committed);
        } else if (!autoCommit) {
            rollback(connection);
        }

    }
}

From source file:edu.ku.brc.specify.plugins.ipadexporter.VerifyCollectionDlg.java

/**
 * /*w w  w .  jav  a  2 s . c  om*/
 */
private void processResults() {
    //loadAndPushResourceBundle("stats");

    RelationshipType paleoRelType = isCollectionPaleo ? ExportPaleo.discoverPaleRelationshipType()
            : RelationshipType.eTypeError;

    boolean hasCritical = false;

    UIRegistry.setDoShowAllResStrErors(false);
    //logMsg("Verifying the Collection...");

    File tmpFile = ipadExporter.getConfigFile(VERIFY_XML);
    if (tmpFile != null && tmpFile.exists()) {
        Statement stmt0 = null;
        try {
            Element root = XMLHelper.readFileToDOM4J(tmpFile);
            if (root != null) {
                ArrayList<String> okMsgs = new ArrayList<String>();
                ArrayList<String> warnMsgs = new ArrayList<String>();
                ArrayList<String> criticalMsgs = new ArrayList<String>();
                int issueCnt = 0;

                String mainFont = "<font face='verdana' color='black'>";
                String headHTML = "<htmL><head></head><body bgcolor='#EEEEEE'>" + mainFont;
                StringBuilder sb = new StringBuilder(headHTML);
                htmlPane.setText(sb.toString() + "<BR><BR>Verifying collection...</font></body></html>");

                List<?> items = root.selectNodes("eval"); //$NON-NLS-1$

                stmt0 = DBConnection.getInstance().getConnection()
                        .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                stmt0.setFetchSize(Integer.MIN_VALUE);

                for (Iterator<?> capIter = items.iterator(); capIter.hasNext();) {
                    Element fieldNode = (Element) capIter.next();
                    //String  name      = fieldNode.attributeValue("name"); //$NON-NLS-1$
                    String desc = fieldNode.attributeValue("desc"); //$NON-NLS-1$
                    String sql = fieldNode.getTextTrim();
                    String cond = fieldNode.attributeValue("cond");
                    String vStr = fieldNode.attributeValue("val");
                    String isFmt = fieldNode.attributeValue("fmt");
                    String stop = fieldNode.attributeValue("stop");
                    boolean doStop = stop != null && stop.equals("true");

                    String display = fieldNode.attributeValue("display");
                    boolean doDsp = display == null || display.equals("true");

                    String paleo = fieldNode.attributeValue("isPaleo");
                    boolean isPaleo = paleo != null && paleo.equals("true");
                    if (isPaleo && !isCollectionPaleo)
                        continue;

                    String paleoTypeStr = fieldNode.attributeValue("paleotype"); //$NON-NLS-1$
                    if (isCollectionPaleo && StringUtils.isNotEmpty(paleoTypeStr)) {
                        if (paleoRelType != paleoLookupHash.get(paleoTypeStr)) {
                            continue;
                        }
                    }

                    sql = ipadExporter.adjustSQL(sql);

                    Object rv = BasicSQLUtils.querySingleObj(sql);
                    Integer retVal = cnvToInt(rv);

                    boolean isError = false;
                    if (retVal != null && StringUtils.isNotEmpty(cond) && StringUtils.isNotEmpty(vStr)) {
                        Integer value = cnvToInt(vStr);
                        if (value != null) {
                            if (cond.equals(">")) {
                                isError = retVal.intValue() > value.intValue();
                            } else if (cond.equals("=")) {
                                isError = retVal.intValue() == value.intValue();
                            } else if (cond.equals("<")) {
                                isError = retVal.intValue() < value.intValue();
                            }
                        }
                    }
                    /*
                                            String fontSt = isError ? "<font color='"+(doStop ? "red" : "orange")+"'>" : "";
                                            String fontEn = isError ? "</font>" : "";
                                            if (StringUtils.isNotEmpty(isFmt) && isFmt.equalsIgnoreCase("true"))
                                            {
                                              sb.append(String.format("<LI>%s%s%s</LI>", fontSt, String.format(desc,  retVal), fontEn));
                                              issueCnt++;
                                            } else
                                            {
                                               sb.append(String.format("<LI>%s%s%s</LI>", fontSt, desc, fontEn));
                                               issueCnt++;
                                            }                        
                     */
                    String fullMsg;
                    if (StringUtils.isNotEmpty(isFmt) && isFmt.equalsIgnoreCase("true")) {
                        fullMsg = String.format(desc, retVal);
                    } else {
                        fullMsg = desc;
                    }

                    if (isError) {
                        if (doStop) {
                            criticalMsgs.add(fullMsg);
                            hasCritical = true;
                        } else {
                            warnMsgs.add(fullMsg);
                        }

                    } else if (doDsp) {
                        okMsgs.add(fullMsg);
                    }

                    issueCnt++;
                    //worker.firePropertyChange(PROGRESS, 0, cnt);
                }
                stmt0.close();

                sb = new StringBuilder(headHTML);
                if (issueCnt == 0) {
                    sb.append("<BR><BR>There were no issues to report.");
                } else {
                    listMsgs(sb, "Passed", okMsgs, "green", true);
                    listMsgs(sb, "Warnings", warnMsgs, "yellow", true);
                    listMsgs(sb, "Critical Errors - Cannot proceed.", criticalMsgs, "red", true);
                }
                sb.append(mainFont + "<BR>Verification Complete.<BR><BR></font></body></html>");

                htmlPane.setText(sb.toString());

                // For external report
                sb = new StringBuilder("<htmL><head><title>Collection Verification</title></head><body>");
                listMsgs(sb, "Passed", okMsgs, "green", false);
                listMsgs(sb, "Warnings", warnMsgs, "yellow", false);
                listMsgs(sb, "Critical Errors - Cannot proceed.", criticalMsgs, "red", false);
                sb.append("</body></html>");
                try {
                    TableWriter tblWriter = new TableWriter(reportPath, "Collection Verification Report", true);
                    tblWriter.println(sb.toString());
                    tblWriter.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();

        } finally {
            try {
                if (stmt0 != null)
                    stmt0.close();
            } catch (Exception ex) {
            }
        }
    }
    okBtn.setEnabled(!hasCritical);
}

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

/**
 * Gets the preparedStatement attribute of the DatabaseConnection object
 * /*from  ww  w.  ja v  a 2 s.  com*/
 * @param str
 *          Description of the Parameter
 * @return The preparedStatement value
 */
public java.sql.PreparedStatement getPreparedStatement(String str) {
    try {

        PreparedStatement st = connect.prepareStatement(str, ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        return st;
    } catch (SQLException ex) {
        errorException = ex;
        return null;
    }
}