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:nl.b3p.viewer.ViewerIntegrationTest.java

/**
 * test if the database has the right metadata version.
 *
 * @throws SQLException if something goes wrong executing the query
 * @throws ClassNotFoundException if the postgres driver cannot be found.
 *///w  w w  . j av  a 2  s .com
@Test
public void testMetadataVersion() throws SQLException, ClassNotFoundException {
    // get 'database_version' from table metadata and check that is has the value of 'n'
    Connection connection = DriverManager.getConnection(databaseprop.getProperty("testdb.url"),
            databaseprop.getProperty("testdb.username"), databaseprop.getProperty("testdb.password"));
    ResultSet rs = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
            .executeQuery("SELECT config_value FROM metadata WHERE config_key = 'database_version'");

    String actual_config_value = "-1";
    while (rs.next()) {
        actual_config_value = rs.getString("config_value");
    }
    assertThat("There is only one 'database_version' record (first and last should be same record).",
            rs.isLast(), equalTo(rs.isFirst()));

    rs.close();
    connection.close();

    assertEquals("The database version should be the same.", DatabaseSynchronizer.getUpdateNumber(),
            actual_config_value);
}

From source file:com.itemanalysis.jmetrik.graph.density.DensityAnalysis.java

public XYSeriesCollection summarize() throws SQLException, IllegalArgumentException {
    Statement stmt = null;/*w w  w. j  a v a  2 s .c  o m*/
    ResultSet rs = null;
    TreeMap<String, ResizableDoubleArray> data = new TreeMap<String, ResizableDoubleArray>();

    //set progress bar information
    int nrow = 0;
    JmetrikPreferencesManager pref = new JmetrikPreferencesManager();
    String dbType = pref.getDatabaseType();
    if (DatabaseType.APACHE_DERBY.toString().equals(dbType)) {
        JmetrikDatabaseFactory dbFactory = new JmetrikDatabaseFactory(DatabaseType.APACHE_DERBY);
        nrow = dao.getRowCount(conn, tableName);
    } else {
        //add other databases here when functionality is added
    }
    maxProgress = (double) nrow;

    Table sqlTable = new Table(tableName.getNameForDatabase());
    SelectQuery select = new SelectQuery();
    select.addColumn(sqlTable, variable.getName().nameForDatabase());
    if (hasGroupingVariable)
        select.addColumn(sqlTable, groupVar.getName().nameForDatabase());
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery(select.toString());

    String conditionalName = "";
    ResizableDoubleArray cData = null;
    double value = Double.NaN;

    while (rs.next()) {
        if (groupVar != null) {
            String groupName = rs.getString(groupVar.getName().nameForDatabase());
            if (rs.wasNull()) {
                groupName = "";
            }
            conditionalName = groupName;
        } else {
            conditionalName = "Series 1";
        }

        cData = data.get(conditionalName);
        if (cData == null) {
            cData = new ResizableDoubleArray((int) maxProgress);
            data.put(conditionalName, cData);
        }
        value = rs.getDouble(variable.getName().nameForDatabase());
        if (!rs.wasNull()) {
            cData.addElement(value);
        }
        updateProgress();
    }
    rs.close();
    stmt.close();

    String kType = command.getSelectOneOption("kernel").getSelectedArgument();
    double adjustment = command.getFreeOption("adjust").getDouble();
    KernelFactory kernelFactory = new KernelFactory(kType);

    KernelFunction kernelFunction = kernelFactory.getKernelFunction();
    Bandwidth bandwidth = null;
    KernelDensity density = null;
    UniformDistributionApproximation uniform = null;
    Min min = new Min();
    Max max = new Max();
    double[] x = null;

    this.firePropertyChange("progress-ind-on", null, null);

    XYSeriesCollection seriesCollection = new XYSeriesCollection();
    XYSeries series = null;
    for (String s : data.keySet()) {
        series = new XYSeries(s);
        x = data.get(s).getElements();
        bandwidth = new ScottsBandwidth(x, adjustment);
        uniform = new UniformDistributionApproximation(min.evaluate(x), max.evaluate(x), KERNEL_POINTS);
        density = new KernelDensity(kernelFunction, bandwidth, uniform);

        double[] dens = density.evaluate(x);
        double[] points = density.getPoints();
        for (int i = 0; i < dens.length; i++) {
            series.add(points[i], dens[i]);
        }
        seriesCollection.addSeries(series);
    }
    return seriesCollection;

}

From source file:com.github.woonsan.jdbc.jcr.impl.JcrJdbcResultSetTest.java

@Test
public void testExecuteSQLQuery() throws Exception {
    Statement statement = getConnection().createStatement();
    ResultSet rs = statement.executeQuery(SQL_EMPS);
    assertSame(statement, rs.getStatement());

    assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
    assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
    assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, rs.getHoldability());

    assertFalse(rs.isClosed());//from   w ww  .j  a v a2s. co  m
    assertTrue(rs.isBeforeFirst());
    assertFalse(rs.isAfterLast());

    assertEquals(1, rs.findColumn("empno"));
    assertEquals(2, rs.findColumn("ename"));
    assertEquals(3, rs.findColumn("salary"));
    assertEquals(4, rs.findColumn("hiredate"));

    int count = printResultSet(rs);

    assertEquals(getEmpRowCount(), count);
    assertFalse(rs.isBeforeFirst());
    assertTrue(rs.isAfterLast());
    rs.close();
    assertTrue(rs.isClosed());

    statement.close();
    assertTrue(statement.isClosed());
}

From source file:com.baidu.rigel.biplatform.tesseract.dataquery.service.impl.SqlDataQueryServiceImpl.java

/**
 * ?SQL??resultRecord list/*from  w  ww  .j  av a2s  .c  om*/
 * @param sqlQuery
 * @param dataSource
 * @param limitStart
 * @param limitEnd
 * @return
 */
private SearchIndexResultSet querySqlList(SqlQuery sqlQuery, DataSource dataSource, long limitStart,
        long limitEnd) {
    long current = System.currentTimeMillis();
    if (sqlQuery == null || dataSource == null || limitEnd < 0) {
        throw new IllegalArgumentException();
    }

    sqlQuery.setLimitMap(limitStart, limitEnd);

    this.initJdbcTemplate(dataSource);

    Meta meta = new Meta(sqlQuery.getSelectList().toArray(new String[0]));
    SearchIndexResultSet resultSet = new SearchIndexResultSet(meta, 1000000);

    jdbcTemplate.query(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pstmt = con.prepareStatement(sqlQuery.toSql(), ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);
            if (con.getMetaData().getDriverName().toLowerCase().contains("mysql")) {
                pstmt.setFetchSize(Integer.MIN_VALUE);
            }
            return pstmt;
        }
    }, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet rs) throws SQLException {
            List<Object> fieldValues = new ArrayList<Object>();
            String groupBy = "";
            for (String select : sqlQuery.getSelectList()) {
                fieldValues.add(rs.getObject(select));
                if (sqlQuery.getGroupBy() != null && sqlQuery.getGroupBy().contains(select)) {
                    groupBy += rs.getString(select) + ",";
                }
            }

            SearchIndexResultRecord record = new SearchIndexResultRecord(
                    fieldValues.toArray(new Serializable[0]), groupBy);
            resultSet.addRecord(record);
        }
    });
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "querySqlList",
            "[sqlQuery:" + sqlQuery.toSql() + "][dataSource:" + dataSource + "][limitStart:" + limitStart
                    + "][limitEnd:" + limitEnd + "] cost" + (System.currentTimeMillis() - current + "ms!")));
    return resultSet;
}

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

private ResizableDoubleArray getData() throws SQLException {
    Statement stmt = null;/*from   w  w  w .  ja  v a  2 s .  c om*/
    ResultSet rs = null;
    ResizableDoubleArray data = new ResizableDoubleArray((int) (maxProgress / 2.0));

    try {
        //connect to table to create data set to be ranked
        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        select.addColumn(sqlTable, variable.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery(select.toString());

        String vNameDb = variable.getName().nameForDatabase();

        double x = Double.NaN;
        int dbIndex = 0;//row position index for all records in db
        while (rs.next()) {
            x = rs.getDouble(vNameDb);
            if (!rs.wasNull()) {
                if (ascending) {
                    data.addElement(x);//ascending order
                } else {
                    data.addElement(-x);//descending order
                }

            } else {
                missingIndex.add(dbIndex);
            }
            dbIndex++;
            updateProgress();
        }
        return data;
    } catch (SQLException ex) {
        throw ex;
    } finally {
        if (rs != null)
            rs.close();
        if (stmt != null)
            stmt.close();

    }
}

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

public void createBlobDef(MSSBamAuthorization Authorization, MSSBamBlobDefBuff Buff) {
    final String S_ProcName = "createBlobDef ";
    try {//from   w ww.ja  v  a2 s.  co m
        Connection cnx = schema.getCnx();
        long Id = Buff.getRequiredId();
        int MaxLen = Buff.getRequiredMaxLen();
        byte[] InitValue = Buff.getOptionalInitValue();
        byte[] DefaultValue = Buff.getOptionalDefaultValue();
        byte[] NullValue = Buff.getOptionalNullValue();
        byte[] UnknownValue = Buff.getOptionalUnknownValue();
        String sql = "INSERT INTO mssbam110.blob_def( " + "id, " + "maxlen, " + "initval, " + "defval, "
                + "nullval, " + "unknownval" + " )" + "VALUES ( " + Id + ", " + MaxLen + ", "
                + MSSBamPg8Schema.getBlobString(InitValue) + ", " + MSSBamPg8Schema.getBlobString(DefaultValue)
                + ", " + MSSBamPg8Schema.getBlobString(NullValue) + ", "
                + MSSBamPg8Schema.getBlobString(UnknownValue) + " )";
        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);
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    }
}

From source file:SyncMusicServlet.java

private void processSongData(String androidId, String title, String album, String artist, String genre) {
    Connection conn = null;//  ww w. j a  va  2  s . c  o  m
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {

        Class.forName(JDBC_DRIVER);
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        // Get the albumId
        String sql = "select album_id from album where album_title='" + album + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        int albumId = rs.getInt("album_id");

        sql = "select * from song where song_title = '" + title.replaceAll("'", "\u0027") + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        if (rs.getRow() == 0) {

            // Insert Song
            pstmt = conn.prepareStatement(
                    "insert into song (song_title, genre, artist_name, album_id) values (?, ?, ?, ?)");
            pstmt.setString(1, title.replaceAll("'", "\u0027"));
            pstmt.setString(2, genre);
            pstmt.setString(3, artist);
            pstmt.setInt(4, albumId);
            pstmt.executeUpdate();
        }

        // Get Song Id
        sql = "select song_id from song where song_title='" + title.replaceAll("'", "\u0027") + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        int songId = rs.getInt("song_id");

        // Check if user_music_data entry exist
        sql = "select * from user_music_data where song_id=" + songId + " AND android_id='" + androidId + "'";
        rs = stmt.executeQuery(sql);
        rs.next();
        if (rs.getRow() == 0) {
            // Insert into user_music_data
            sql = "insert into user_music_data (android_id, song_id) values ('" + androidId + "', " + songId
                    + ")";
            stmt.executeUpdate(sql);
        }
        //out.print(resultJSON);
    } catch (Exception se) {
        //out.println("Exception preparing or processing query: " + se);
        se.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {

        }
    }
}

From source file:net.solarnetwork.node.dao.jdbc.AbstractBatchableJdbcDao.java

private BatchResult batchProcessInternal(final BatchCallback<T> callback, final BatchOptions options) {
    final String querySql = getBatchJdbcStatement(options);
    final AtomicInteger rowCount = new AtomicInteger(0);
    getJdbcTemplate().execute(new ConnectionCallback<Object>() {

        @Override//  ww w . j a  v  a 2 s . c om
        public net.solarnetwork.node.dao.BatchableDao.BatchResult doInConnection(Connection con)
                throws SQLException, DataAccessException {
            PreparedStatement queryStmt = null;
            ResultSet queryResult = null;
            try {
                queryStmt = con.prepareStatement(querySql,
                        (options.isUpdatable() ? ResultSet.TYPE_SCROLL_SENSITIVE : ResultSet.TYPE_FORWARD_ONLY),
                        (options.isUpdatable() ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY),
                        ResultSet.CLOSE_CURSORS_AT_COMMIT);
                queryResult = queryStmt.executeQuery();
                while (queryResult.next()) {
                    T entity = getBatchRowEntity(options, queryResult, rowCount.incrementAndGet());
                    BatchCallbackResult rowResult = callback.handle(entity);
                    switch (rowResult) {
                    case CONTINUE:
                        break;
                    case STOP:
                        return null;
                    case DELETE:
                        queryResult.deleteRow();
                        break;
                    case UPDATE:
                    case UPDATE_STOP:
                        updateBatchRowEntity(options, queryResult, rowCount.intValue(), entity);
                        queryResult.updateRow();
                        if (rowResult == BatchCallbackResult.UPDATE_STOP) {
                            return null;
                        }
                        break;
                    }
                }
            } finally {
                if (queryResult != null) {
                    queryResult.close();
                }
                if (queryStmt != null) {
                    queryStmt.close();
                }
            }

            return null;
        }
    });
    return new BasicBatchResult(rowCount.intValue());
}

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

public void createBoolDef(MSSBamAuthorization Authorization, MSSBamBoolDefBuff Buff) {
    final String S_ProcName = "createBoolDef ";
    try {//from  w  w  w  .ja  va2  s.c  o m
        Connection cnx = schema.getCnx();
        long Id = Buff.getRequiredId();
        Boolean InitValue = Buff.getOptionalInitValue();
        Boolean DefaultValue = Buff.getOptionalDefaultValue();
        String FalseString = Buff.getOptionalFalseString();
        String TrueString = Buff.getOptionalTrueString();
        String NullString = Buff.getOptionalNullString();
        String sql = "INSERT INTO mssbam110.bool_def( " + "id, " + "initval, " + "defval, " + "falsestring, "
                + "truestring, " + "nullstring" + " )" + "VALUES ( " + Id + ", "
                + ((InitValue == null) ? "null" : (InitValue ? "true" : "false")) + ", "
                + ((DefaultValue == null) ? "null" : (DefaultValue ? "true" : "false")) + ", "
                + MSSBamPg8Schema.getQuotedString(FalseString) + ", "
                + MSSBamPg8Schema.getQuotedString(TrueString) + ", "
                + MSSBamPg8Schema.getQuotedString(NullString) + " )";
        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);
        }
    } catch (SQLException e) {
        throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
    }
}

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

@Override
public void afterPropertiesSet() throws Exception {
    if (!scalabilityManager.getClearDB()) {
        return;/*from www.j a v  a 2 s .co  m*/
    }
    PreparedStatement ps = datasource.getConnection().prepareStatement(
            "SELECT TRIGGER_NAME FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_NAME LIKE 'SYM_%';",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
        PreparedStatement ps2 = datasource.getConnection()
                .prepareStatement("DROP TRIGGER " + rs.getString("TRIGGER_NAME"));
        ps2.execute();
        ps2.close();
    }
    ps.close();

    ps = datasource.getConnection().prepareStatement(
            "SELECT CONSTRAINT_NAME, TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME LIKE 'SYM_%';",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = ps.executeQuery();
    while (rs.next()) {
        PreparedStatement ps2 = datasource.getConnection().prepareStatement("ALTER TABLE "
                + rs.getString("TABLE_NAME") + " DROP CONSTRAINT " + rs.getString("CONSTRAINT_NAME"));
        ps2.execute();
        ps2.close();
    }
    ps.close();

    ps = datasource.getConnection().prepareStatement(
            "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'SYM_%';",
            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

    rs = ps.executeQuery();
    while (rs.next()) {
        PreparedStatement ps2 = datasource.getConnection()
                .prepareStatement("DROP TABLE " + rs.getString("TABLE_NAME"));
        ps2.execute();
        ps2.close();
    }
    ps.close();
}