Example usage for java.sql ResultSet CONCUR_READ_ONLY

List of usage examples for java.sql ResultSet CONCUR_READ_ONLY

Introduction

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

Prototype

int CONCUR_READ_ONLY

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

Click Source Link

Document

The constant indicating the concurrency mode for a ResultSet object that may NOT be updated.

Usage

From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8AttachmentTable.java

public void createAttachment(MSSBamAuthorization Authorization, MSSBamAttachmentBuff Buff) {
    final String S_ProcName = "createAttachment ";
    if (!schema.isTransactionOpen()) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Transaction not open");
    }//from  ww  w  .j a  va  2  s .  c  o m
    try {
        Connection cnx = schema.getCnx();
        long AttachmentId = schema.nextAttachmentIdGen();
        long ContactId = Buff.getRequiredContactId();
        String Description = Buff.getRequiredDescription();
        Short MimeTypeId = Buff.getOptionalMimeTypeId();
        String Attachment = Buff.getRequiredAttachment();
        int Revision = 1;
        String sql = "INSERT INTO mssbam110.Attachment( " + "attachmentid, " + "contactid, " + "description, "
                + "mimetypeid, " + "attachment" + ", revision )" + "VALUES ( " + AttachmentId + ", " + ContactId
                + ", " + MSSBamPg8Schema.getQuotedString(Description) + ", "
                + ((MimeTypeId == null) ? "null" : MimeTypeId.toString()) + ", "
                + MSSBamPg8Schema.getQuotedString(Attachment) + ", " + Integer.toString(Revision) + " )";
        Statement stmt = cnx.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        int rowsAffected = stmt.executeUpdate(sql);
        if (rowsAffected != 1) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected 1 row to be affected by insert, not " + rowsAffected);
        }
        Buff.setRequiredAttachmentId(AttachmentId);
        Buff.setRequiredRevision(Revision);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    }
}

From source file:com.itemanalysis.jmetrik.stats.descriptives.DescriptiveAnalysis.java

public void summarize() throws SQLException {
    Statement stmt = null;//from   w  w  w. ja v a2s.c o  m
    ResultSet rs = null;

    DescriptiveStatistics temp = null;

    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    for (VariableAttributes v : variables) {
        select.addColumn(sqlTable, v.getName().nameForDatabase());
    }
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(select.toString());

    double value = Double.NaN;
    while (rs.next()) {
        for (VariableAttributes v : variables) {
            temp = data.get(v);
            if (temp == null) {
                temp = new DescriptiveStatistics();
                data.put(v, temp);
            }

            //only increment for non null doubles
            value = rs.getDouble(v.getName().nameForDatabase());
            if (!rs.wasNull()) {
                temp.addValue(value);
            }
        }
        updateProgress();
    }

    rs.close();
    stmt.close();

    for (VariableAttributes v : data.keySet()) {
        publishTable(v);
    }

}

From source file:com.itemanalysis.jmetrik.stats.frequency.FrequencyAnalysis.java

public void summarize() throws SQLException {
    Statement stmt = null;/*from  www.  ja  v a  2  s .  c om*/
    ResultSet rs = null;

    frequencyTables = new LinkedHashMap<VariableAttributes, Frequency>();
    Frequency temp = null;

    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    for (VariableAttributes v : variables) {
        select.addColumn(sqlTable, v.getName().nameForDatabase());
    }
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(select.toString());

    String strValue = "";
    double dblValue = 0;
    while (rs.next()) {
        for (VariableAttributes v : variables) {
            temp = frequencyTables.get(v);
            if (temp == null) {
                temp = new Frequency();
                frequencyTables.put(v, temp);
            }
            if (v.getType().getDataType() == DataType.STRING) {
                strValue = rs.getString(v.getName().nameForDatabase());
                if (!rs.wasNull() && !"".equals(strValue)) {
                    temp.addValue(strValue);
                }
            } else {
                dblValue = rs.getDouble(v.getName().nameForDatabase());
                if (!rs.wasNull()) {
                    temp.addValue(dblValue);
                }
            }
        }
        updateProgress();
    }
    rs.close();
    stmt.close();

    for (VariableAttributes v : frequencyTables.keySet()) {
        publishTable(v);
    }

}

From source file:main.export.sql.DocBuilder.java

@SuppressWarnings("unchecked")
public void execute() throws ClassNotFoundException, InstantiationException, IllegalAccessException,
        SQLException, UnsupportedEncodingException, IOException, HttpException {

    String url = importer.getConfig().dataSources.get(null).getProperty("url");
    String user = importer.getConfig().dataSources.get(null).getProperty("user");
    String password = importer.getConfig().dataSources.get(null).getProperty("password");
    batchSize = Integer.valueOf(importer.getConfig().dataSources.get(null).getProperty("batch-size"));
    Entity rootEntity = importer.getConfig().document.entities.get(0);
    String driverName = importer.getConfig().dataSources.get(null).getProperty(DRIVER);

    // Set the fetch size depending on SQL type
    if (batchSize == -1 && driverName.contains("mysql"))
        batchSize = Integer.MIN_VALUE;
    else if (batchSize == -1)
        batchSize = 0;// www  . j a  va2s  . c  o  m

    Class.forName(driverName).newInstance();
    conn = DriverManager.getConnection(url, user, password);
    subConnection = DriverManager.getConnection(url, user, password);

    // set the PK for future use
    importer.getWriter().setPrimaryKey(rootEntity.pk);

    if (rootEntity != null && rootEntity.isDocRoot) {
        String rootQuery = rootEntity.allAttributes.get("query");
        stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        stmt.setMaxRows(0);
        stmt.setFetchSize(batchSize);
        rs = stmt.executeQuery(rootQuery);
        int i = 0;
        List<Map<String, Object>> entityList = new ArrayList<Map<String, Object>>();

        long t1 = System.currentTimeMillis();
        while (rs.next()) {
            if (i == importer.getAutoCommitSize()) {
                long t2 = System.currentTimeMillis();
                log.info("Time taken to Read " + i + " documents from SQL : " + (t2 - t1) + " ms");
                // FIXME Remove ouput
                System.out.println("Time taken to Read " + i + " documents from SQL : " + (t2 - t1) + " ms");
                importer.getWriter().writeToNoSQL(entityList);
                entityList = new ArrayList<Map<String, Object>>();

                i = 0;
                t1 = System.currentTimeMillis();

            }
            params = new HashMap<String, String>();
            entityList.add(getFields(processor.toMap(rs), rs, rootEntity, null, null));
            i++;
        }

        importer.getWriter().writeToNoSQL(entityList);
    }

    conn.close();
    subConnection.close();
}

From source file:com.github.adejanovski.cassandra.jdbc.CassandraStatement.java

CassandraStatement(CassandraConnection con, String cql, int resultSetType, int resultSetConcurrency,
        int resultSetHoldability) throws SQLException {
    this.connection = con;
    this.cql = cql;
    this.batchQueries = Lists.newArrayList();

    this.consistencyLevel = con.defaultConsistencyLevel;

    if (!(resultSetType == ResultSet.TYPE_FORWARD_ONLY || resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE
            || resultSetType == ResultSet.TYPE_SCROLL_SENSITIVE))
        throw new SQLSyntaxErrorException(BAD_TYPE_RSET);
    this.resultSetType = resultSetType;

    if (!(resultSetConcurrency == ResultSet.CONCUR_READ_ONLY
            || resultSetConcurrency == ResultSet.CONCUR_UPDATABLE))
        throw new SQLSyntaxErrorException(BAD_TYPE_RSET);
    this.resultSetConcurrency = resultSetConcurrency;

    if (!(resultSetHoldability == ResultSet.HOLD_CURSORS_OVER_COMMIT
            || resultSetHoldability == ResultSet.CLOSE_CURSORS_AT_COMMIT))
        throw new SQLSyntaxErrorException(BAD_HOLD_RSET);
    this.resultSetHoldability = resultSetHoldability;
}

From source file:org.apache.jena.jdbc.remote.results.TestRemoteEndpointResultsWithAuth.java

@Override
protected ResultSet createResults(Dataset ds, String query, int resultSetType) throws SQLException {
    TestUtils.copyToRemoteDataset(ds, FusekiTestAuth.serviceGSP(), client);
    Statement stmt = connection.createStatement(resultSetType, ResultSet.CONCUR_READ_ONLY);
    return stmt.executeQuery(query);
}

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

/**
 * @param tblName/*from w  ww  .  j  a v a  2s  .  c o m*/
 * @return
 */
public int getMapCount(final String tblName) {
    Statement cntStmt = null;
    ResultSet rs = null;

    try {
        Integer count = 0;
        cntStmt = oldConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = cntStmt.executeQuery("select count(*) from " + tblName);
        if (rs.first()) {
            count = rs.getInt(1);
            if (count == null) {
                return 0;
            }
        }

        return count;

    } catch (SQLException ex) {
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (cntStmt != null)
                cntStmt.close();
        } catch (Exception ex) {
        }
    }
    return 0;
}

From source file:gridool.mapred.db.task.DBMapShuffleTaskBase.java

protected final Serializable execute() throws GridException {
    int numShuffleThreads = shuffleThreads();
    this.shuffleExecPool = (numShuffleThreads <= 0) ? new DirectExecutorService()
            : ExecutorFactory.newFixedThreadPool(numShuffleThreads, "Gridool#Shuffle", true);
    this.shuffleSink = new BoundedArrayQueue<OUT_TYPE>(shuffleUnits());

    // execute a query
    final Connection conn;
    try {//ww w .ja  va  2 s. com
        conn = jobConf.getConnection(false);
        configureConnection(conn);
    } catch (ClassNotFoundException e) {
        LOG.error(e);
        throw new GridException(e);
    } catch (SQLException e) {
        LOG.error(e);
        throw new GridException(e);
    }
    assert (conn != null);
    final String query = jobConf.getInputQuery();
    final Statement statement;
    final ResultSet results;
    try {
        statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        results = statement.executeQuery(query);
    } catch (SQLException e) {
        try {
            conn.close();
        } catch (SQLException sqle) {// avoid
            LOG.debug(sqle.getMessage());
        }
        LOG.error(e);
        throw new GridException(e);
    }

    try {
        preprocess(conn, results);
    } catch (SQLException e) {
        LOG.error(e);
        throw new GridException(e);
    }

    // Iterate over records
    // process -> shuffle is consequently called
    try {
        while (results.next()) {
            IN_TYPE record = prepareInputRecord();
            readFields(record, results);
            if (!process(record)) {
                break;
            }
        }
    } catch (SQLException e) {
        LOG.error(e);
        throw new GridException(e);
    } finally {
        try {
            statement.close();
        } catch (SQLException e) {
            LOG.debug("failed closing a statement", e);
        }
        try {
            conn.close();
        } catch (SQLException e) {
            LOG.debug("failed closing a connection", e);
        }
    }
    postShuffle();
    return null;
}

From source file:edu.ku.brc.specify.toycode.mexconabio.AnalysisWithGBIFToGBIF.java

@Override
public void process(final int type, final int options) {
    calcMaxScore();/*from  w  ww .  ja v  a 2s .  c  o m*/

    String gbifSQL = "SELECT DISTINCT id, catalogue_number, genus, species, subspecies, latitude, longitude, country, state_province, collector_name, locality, year, month, day, collector_num ";

    String fromClause1a = "FROM raw WHERE collector_num LIKE ? AND year = ? AND genus = ?";
    String fromClause1b = "FROM raw WHERE collector_num IS NULL AND year = ? AND genus = ?";
    //String fromClause2  = "FROM raw WHERE collector_num IS NULL AND year = ? AND month = ? AND genus = ? AND id <> ?";

    //                        1       2           3        4           5         6          7         8           9               10          11       12    13    14      15
    String postSQL = "FROM raw WHERE collector_num IS NOT NULL GROUP BY collector_num, year, genus";
    String srcSQL = "SELECT id, catalogue_number, genus, species, subspecies, latitude, longitude, country, state_province, collector_name, locality, year, month, day, collector_num "
            + postSQL + " ORDER BY collector_num";

    String grphashSQL = "SELECT name FROM group_hash";

    String gbifgbifInsert = "INSERT INTO gbifgbif (reltype, score, GBIFID, SNIBID) VALUES (?,?,?,?)";

    Statement stmt = null;
    PreparedStatement gStmt1a = null;
    PreparedStatement gStmt1b = null;
    //PreparedStatement gStmt2  = null;
    PreparedStatement gsStmt = null;

    Object[] refRow = new Object[NUM_FIELDS];
    Object[] cmpRow = new Object[NUM_FIELDS];

    long totalRecs = BasicSQLUtils.getCount(dbSrcConn, "SELECT COUNT(*) FROM group_hash");
    long procRecs = 0;
    long startTime = System.currentTimeMillis();
    int secsThreshold = 0;

    String blank = "X?";

    PrintWriter pw = null;
    try {
        pw = new PrintWriter("scoring_gbifgbif.log");

        gStmt1a = dbGBIFConn.prepareStatement(gbifSQL + fromClause1a);
        gStmt1b = dbGBIFConn.prepareStatement(gbifSQL + fromClause1b);

        //gStmt2 = dbGBIFConn.prepareStatement(gbifSQL + fromClause2);
        gsStmt = dbDstConn.prepareStatement(gbifgbifInsert);

        stmt = dbSrcConn.createStatement(ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(Integer.MIN_VALUE);

        System.out.println("Starting Query... " + totalRecs);
        pw.println("Starting Query... " + totalRecs);
        System.out.flush();
        pw.flush();

        HashSet<Integer> idHash = new HashSet<Integer>();
        int writeCnt = 0;
        ResultSet rs = stmt.executeQuery(grphashSQL);

        System.out
                .println(String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                        totalRecs, maxScore, thresholdScore));
        pw.println(String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                totalRecs, maxScore, thresholdScore));
        System.out.flush();
        pw.flush();

        Vector<Object[]> group = new Vector<Object[]>();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        while (rs.next()) {
            String[] tokens = StringUtils.split(rs.getString(1), '_');

            String colNum = tokens[0].trim();
            String year = tokens[1].trim();
            String genus = tokens[2].trim();

            if (StringUtils.isEmpty(colNum) || colNum.equals(blank))
                colNum = null;
            if (StringUtils.isEmpty(year) || year.equals(blank))
                year = null;
            if (StringUtils.isEmpty(genus) || genus.equals(blank))
                genus = null;

            PreparedStatement gStmt1;
            if (colNum != null) {
                gStmt1 = gStmt1a;
                gStmt1.setString(1, "%" + colNum + "%");
            } else {
                gStmt1 = gStmt1b;
                gStmt1.setString(1, null);
            }
            gStmt1.setString(2, year);
            gStmt1.setString(3, genus);
            ResultSet gRS = gStmt1.executeQuery();

            ids.clear();
            int maxNonNullTot = -1;
            int maxNonNullInx = -1;
            int inx = 0;
            while (gRS.next()) {

                Object[] row = getRow();
                int cnt = fillRowWithScore(row, gRS);
                if (cnt > maxNonNullTot) {
                    maxNonNullInx = inx;
                    maxNonNullTot = cnt;
                }
                group.add(row);
                ids.add(gRS.getInt(1));
                inx++;
            }
            gRS.close();

            if (inx < 2) {
                for (Object[] r : group) {
                    recycleRow(r);
                }
                group.clear();
                continue;
            }

            System.arraycopy(group.get(maxNonNullInx), 0, refRow, 0, refRow.length);

            Integer srcId = ids.get(maxNonNullInx);

            for (int i = 0; i < group.size(); i++) {
                if (i != maxNonNullInx) {
                    int score = score(refRow, group.get(i));

                    if (score > thresholdScore) {
                        writeCnt++;

                        int gbifID = ids.get(i);
                        gsStmt.setInt(1, 1); // reltype
                        gsStmt.setInt(2, score); // score
                        gsStmt.setInt(3, gbifID);
                        gsStmt.setInt(4, srcId);
                        gsStmt.executeUpdate();

                        idHash.add(gbifID);
                    }
                }
            }

            idHash.clear();

            for (Object[] r : group) {
                recycleRow(r);
            }
            group.clear();

            if (gStmt1 == gStmt1b) {
                continue;
            }

            gStmt1 = gStmt1b;
            gStmt1.setString(1, year);
            gStmt1.setString(2, genus);

            gRS = gStmt1.executeQuery();
            while (gRS.next()) {
                fillRowWithScore(cmpRow, gRS);

                int gbifID = gRS.getInt(1);
                if (gbifID == srcId)
                    continue;

                int score = score(refRow, cmpRow);

                if (score > thresholdScore) {
                    writeCnt++;
                    gsStmt.setInt(1, 1); // reltype
                    gsStmt.setInt(2, score); // score
                    gsStmt.setInt(3, gbifID);
                    gsStmt.setInt(4, srcId);
                    gsStmt.executeUpdate();
                }
            }
            gRS.close();

            procRecs++;
            if (procRecs % 500 == 0) {
                long endTime = System.currentTimeMillis();
                long elapsedTime = endTime - startTime;

                double timePerRecord = (elapsedTime / procRecs);

                double hrsLeft = ((totalRecs - procRecs) * timePerRecord) / HRS;

                int seconds = (int) (elapsedTime / 60000.0);
                if (secsThreshold != seconds) {
                    secsThreshold = seconds;

                    String msg = String.format("Elapsed %8.2f hr.mn   Percent: %6.3f  Hours Left: %8.2f ",
                            ((double) (elapsedTime)) / HRS, 100.0 * ((double) procRecs / (double) totalRecs),
                            hrsLeft);
                    System.out.println(msg);
                    pw.println(msg);
                    pw.flush();
                }
            }
        }
        rs.close();

        System.out.println("Done.");
        pw.println("Done.");

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (gStmt1a != null) {
                gStmt1a.close();
            }
            if (gStmt1b != null) {
                gStmt1b.close();
            }
            /*if (gStmt2 != null)
            {
            gStmt2.close();
            }*/
        } catch (Exception ex) {

        }
    }
    System.out.println("Done.");
    pw.println("Done.");
    pw.flush();
    pw.close();
}

From source file:net.sourceforge.msscodefactory.v1_10.MSSBamPg8.MSSBamPg8AddressTable.java

public void createAddress(MSSBamAuthorization Authorization, MSSBamAddressBuff Buff) {
    final String S_ProcName = "createAddress ";
    if (!schema.isTransactionOpen()) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Transaction not open");
    }//from  w w w.j a va 2s. c o m
    try {
        Connection cnx = schema.getCnx();
        long AddressId = schema.nextAddressIdGen();
        long ContactId = Buff.getRequiredContactId();
        String Description = Buff.getRequiredDescription();
        String AddrLine1 = Buff.getOptionalAddrLine1();
        String AddrLine2 = Buff.getOptionalAddrLine2();
        String City = Buff.getOptionalCity();
        String State = Buff.getOptionalState();
        String Country = Buff.getOptionalCountry();
        String PostalCode = Buff.getOptionalPostalCode();
        int Revision = 1;
        String sql = "INSERT INTO mssbam110.Address( " + "addressid, " + "contactid, " + "description, "
                + "addrline1, " + "addrline2, " + "city, " + "state, " + "country, " + "postalcode"
                + ", revision )" + "VALUES ( " + AddressId + ", " + ContactId + ", "
                + MSSBamPg8Schema.getQuotedString(Description) + ", "
                + MSSBamPg8Schema.getQuotedString(AddrLine1) + ", " + MSSBamPg8Schema.getQuotedString(AddrLine2)
                + ", " + MSSBamPg8Schema.getQuotedString(City) + ", " + MSSBamPg8Schema.getQuotedString(State)
                + ", " + MSSBamPg8Schema.getQuotedString(Country) + ", "
                + MSSBamPg8Schema.getQuotedString(PostalCode) + ", " + Integer.toString(Revision) + " )";
        Statement stmt = cnx.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        int rowsAffected = stmt.executeUpdate(sql);
        if (rowsAffected != 1) {
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "Expected 1 row to be affected by insert, not " + rowsAffected);
        }
        Buff.setRequiredAddressId(AddressId);
        Buff.setRequiredRevision(Revision);
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    }
}