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.glom.SqlUtils.java

public static ResultSet executeQuery(final Connection conn, final String query, int expectedLength)
        throws SQLException {
    // Setup and execute the query. Special care needs to be take to ensure that the results will be based
    // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
    // data. Here's the relevant PostgreSQL documentation:
    // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
    conn.setAutoCommit(false);/*from   w w  w.  j a  v a2 s . c  o m*/

    //TODO: Change this back to ResultSet.TYPE_FORWARD_ONLY when we can use a sane UI component
    //(not JTable) that doesn't need us to jump around the result set or copy its entire contents.
    final Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    if (expectedLength > 0) {
        st.setFetchSize(expectedLength);
    }

    return st.executeQuery(query);
}

From source file:nl.strohalm.cyclos.utils.JDBCWrapper.java

private ResultSet doQuery(final String sql, final int concurrency, final Object... parameters)
        throws SQLException {
    final PreparedStatement ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
            concurrency);/*from   w  w  w .j a  v a  2s  .co  m*/
    setParameters(ps, parameters);
    return ps.executeQuery();
}

From source file:com.norconex.collector.core.data.store.impl.jdbc.JDBCCrawlDataStore.java

@Override
public Iterator<ICrawlData> getCacheIterator() {
    try {//from  w w  w .j  a v  a 2s .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(serializer.getSelectCrawlDataSQL(TABLE_CACHE));
        if (rs == null || !rs.first()) {
            return null;
        }
        rs.beforeFirst();
        return new CrawlDataIterator(TABLE_CACHE, rs, conn, stmt);
    } catch (SQLException e) {
        throw new CrawlDataStoreException("Problem getting database cache iterator.", e);
    }
}

From source file:net.sathis.export.sql.DocBuilder.java

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();//w  ww.j  ava  2 s.  c om
        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:pub.platform.db.DatabaseConnection.java

/**
 * Description of the Method//  w  ww  . j a  v  a 2s .  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:org.apache.openjpa.jdbc.kernel.JDBCFetchConfigurationImpl.java

public JDBCFetchConfiguration setResultSetType(int type) {
    if (type != DEFAULT && type != ResultSet.TYPE_FORWARD_ONLY && type != ResultSet.TYPE_SCROLL_INSENSITIVE
            && type != ResultSet.TYPE_SCROLL_SENSITIVE)
        throw new IllegalArgumentException(_loc.get("bad-resultset-type", Integer.valueOf(type)).getMessage());

    if (type == DEFAULT) {
        JDBCConfiguration conf = getJDBCConfiguration();
        if (conf != null)
            _state.type = conf.getResultSetTypeConstant();
    } else/*from w  w  w  .jav  a 2s.c o  m*/
        _state.type = type;
    return this;
}

From source file:jp.mathes.databaseWiki.db.postgres.PostgresBackend.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private PostgresDocument createEmptyDocument(final Connection conn, final String table, final String name,
        final String db) throws BackendException {
    Statement st = null;/* w  w w  . java  2s.  c  o m*/
    Statement st2 = null;
    ResultSet rs = null;
    ResultSet rs2 = null;
    PostgresDocument doc = new PostgresDocument();
    doc.setTable(this.getSchemaName(table, db) + "." + this.getPlainTableName(table));
    doc.setDatabase(db);
    doc.setName(name);
    try {
        String schema = this.getSchemaName(table, db);
        String plainTable = this.getPlainTableName(table);
        st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

        StringBuilder sb = new StringBuilder("");
        sb.append("select c.column_name, c.column_default, c.data_type, ccu.table_name, ccu.column_name");
        sb.append("  from information_schema.columns c");
        sb.append("  left join information_schema.key_column_usage kcu");
        sb.append("    on kcu.table_schema = c.table_schema and kcu.table_name = c.table_name");
        sb.append("     and kcu.column_name = c.column_name");
        sb.append("  left join information_schema.table_constraints tc");
        sb.append("    on tc.constraint_type='FOREIGN KEY' and tc.table_schema = c.table_schema");
        sb.append("     and tc.table_name = c.table_name and tc.constraint_name = kcu.constraint_name");
        sb.append("  left join information_schema.constraint_column_usage ccu");
        sb.append(
                "    on ccu.constraint_schema = tc.constraint_schema and ccu.constraint_name = tc.constraint_name");
        sb.append("  where c.table_schema='%s' and c.table_name='%s'");
        sb.append("  order by c.ordinal_position");
        String queryString = String.format(sb.toString().replaceAll("[ ]+", " "), schema, plainTable);

        this.logString(queryString, "?");
        rs = st.executeQuery(queryString);
        if (this.getNumRows(rs) == 0) {
            throw new BackendException(String.format("Table %s.%s has no columns which is not supported.",
                    this.getSchemaName(table, db), this.getPlainTableName(table)));
        }

        String nameField = this.getNameField(conn, table, db);
        while (rs.next()) {
            String ctype = rs.getString(3);
            String cname = rs.getString(1);
            PostgresField field = null;
            if ("character varying".equals(ctype)) {
                field = new PostgresField<String>();
                field.setType(FieldType.string);
                field.setValue(rs.getString(2));
            } else if ("text".equals(ctype)) {
                field = new PostgresField<String>();
                field.setType(FieldType.text);
                field.setValue(rs.getString(2));
            } else if ("integer".equals(ctype) || "bigint".equals(ctype) || "smallint".equals(ctype)
                    || "real".equals(ctype)) {
                field = new PostgresField<Integer>();
                field.setType(FieldType.dec);
                field.setValue(rs.getInt(2));
            } else if ("numeric".equals(ctype)) {
                field = new PostgresField<Double>();
                field.setType(FieldType.num);
                field.setValue(rs.getDouble(2));
            } else if ("date".equals(ctype)) {
                field = new PostgresField<Date>();
                field.setType(FieldType.date);
                field.setValue(rs.getDate(2));
            }
            if (field != null) {
                field.setName(cname);
                field.setUsage(FieldUsage.normal);
                if (nameField.equals(cname)) {
                    field.setValue(name);
                } else if ("version".equals(cname)) {
                    field.setUsage(FieldUsage.hidden);
                }

                String foreignTable = rs.getString(4);
                String foreignColumn = rs.getString(5);
                if (!StringUtils.isEmpty(foreignTable) && !StringUtils.isEmpty(foreignColumn)) {
                    st2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    field.setUsage(FieldUsage.fixed);
                    StringBuilder sb2 = new StringBuilder();
                    sb2.append("select distinct \"%s\" from \"%s\" order by \"%s\"");
                    String queryString2 = String.format(sb2.toString().replaceAll("[ ]+", " "), foreignColumn,
                            foreignTable, foreignColumn);
                    this.logString(queryString2, "?");
                    rs2 = st2.executeQuery(queryString2);
                    while (rs2.next()) {
                        field.getAllowedValues().add(rs2.getObject(1));
                    }
                }
                doc.addField(cname, field);
            }
        }
    } catch (SQLException e) {
        throw new BackendException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(rs2);
        DbUtils.closeQuietly(st);
        DbUtils.closeQuietly(st2);
    }
    return doc;
}

From source file:org.wso2.carbon.ml.project.mgt.DatabaseHandler.java

/**
 * Get the project names and created dates, that a tenant is assigned to.
 *
 * @param tenantID     Unique identifier for the tenant.
 * @return             An array of project ID, Name and the created date of the projects 
 *                     associated with a given tenant.
 * @throws             DatabaseHandlerException.
 *//*  w  w  w.j  a va2 s . c o  m*/
public String[][] getTenantProjects(String tenantID) throws DatabaseHandlerException {
    Connection connection = null;
    PreparedStatement getTenantProjectsStatement = null;
    ResultSet result = null;
    String[][] projects = null;
    try {
        connection = dataSource.getConnection();
        connection.setAutoCommit(true);
        getTenantProjectsStatement = connection.prepareStatement(SQLQueries.GET_TENANT_PROJECTS,
                ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        getTenantProjectsStatement.setString(1, tenantID);
        result = getTenantProjectsStatement.executeQuery();
        // create a 2-d string array having the size of the result set
        result.last();
        int size = result.getRow();
        if (size > 0) {
            projects = new String[3][size];
            result.beforeFirst();
            // put the result set to the string array
            for (int i = 0; i < size; i++) {
                result.next();
                projects[0][i] = result.getObject(1).toString();
                projects[1][i] = result.getString(2);
                projects[2][i] = result.getDate(3).toString();
            }
        }
        return projects;
    } catch (SQLException e) {
        MLDatabaseUtil.rollBack(connection);
        throw new DatabaseHandlerException(
                "Error occured while retrieving the projects of user " + tenantID + ": " + e.getMessage(), e);
    } finally {
        // close the database resources
        MLDatabaseUtil.closeDatabaseResources(connection, getTenantProjectsStatement, result);
    }
}

From source file:org.jboss.bqt.framework.AbstractQuery.java

protected Statement createStatement() throws SQLException {
    return this.internalConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
}

From source file:com.itemanalysis.jmetrik.graph.nicc.NonparametricCurveAnalysis.java

private void initializeGridPoints() throws SQLException {
    Statement stmt = null;/*from  w ww.ja  va2  s .co  m*/
    ResultSet rs = null;

    //connect to db
    try {
        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        select.addColumn(sqlTable, regressorVariable.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(select.toString());

        Min min = new Min();
        Max max = new Max();
        Mean mean = new Mean();
        StandardDeviation sd = new StandardDeviation();

        double value = 0.0;
        while (rs.next()) {
            value = rs.getDouble(regressorVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                min.increment(value);
                max.increment(value);
                mean.increment(value);
                sd.increment(value);
            }
            updateProgress();
        }
        rs.close();
        stmt.close();

        //evaluation points
        double sdv = sd.getResult();
        double mn = mean.getResult();
        double lower = mn - 2.5 * sdv;
        double upper = mn + 2.5 * sdv;
        bwAdjustment *= sdv;
        bandwidth = new NonparametricIccBandwidth(sampleSize, bwAdjustment);
        gridPoints = command.getFreeOption("gridpoints").getInteger();
        //            uniformDistributionApproximation = new UniformDistributionApproximation(
        //                    min.getResult(), max.getResult(), gridPoints);
        uniformDistributionApproximation = new UniformDistributionApproximation(lower, upper, gridPoints);

    } catch (SQLException ex) {
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();
    }

}