Example usage for java.sql ResultSet CONCUR_UPDATABLE

List of usage examples for java.sql ResultSet CONCUR_UPDATABLE

Introduction

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

Prototype

int CONCUR_UPDATABLE

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

Click Source Link

Document

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

Usage

From source file:com.taobao.datax.plugins.writer.mysqlwriter.MysqlWriter.java

@Override
public int post(PluginParam param) {
    if (StringUtils.isBlank(this.post))
        return PluginStatus.SUCCESS.value();

    /*/*ww  w .j ava2s  .  c o m*/
     * add by bazhen.csy if (null == this.connection) { throw new
     * DataExchangeException(String.format(
     * "MysqlWriter connect %s failed in post work .", this.host)); }
     */

    Statement stmt = null;
    try {
        this.connection = DBSource.getConnection(this.sourceUniqKey);

        stmt = this.connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        for (String subSql : this.post.split(";")) {
            this.logger.info(String.format("Excute prepare sql %s .", subSql));
            stmt.execute(subSql);
        }

        return PluginStatus.SUCCESS.value();
    } catch (Exception e) {
        throw new DataExchangeException(e.getCause());
    } finally {
        try {
            if (null != stmt) {
                stmt.close();
            }
            if (null != this.connection) {
                this.connection.close();
                this.connection = null;
            }
        } catch (Exception e2) {
        }

    }
}

From source file:DbManager.java

/**
 * Provide the PreparedStatement, given a query.
 * /*w w w .  ja  v  a2  s  .  com*/
 * @param query
 *            the query.
 * @return the PreparedStatement based on the query.
 */
public PreparedStatement prepareStatement(String query) {
    try {
        pstmt = con.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        return pstmt;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.oracle.tutorial.jdbc.CoffeesTable.java

public void modifyPrices(float percentage) throws SQLException {
    Statement stmt = null;/*from w  ww  .  java  2s  . co m*/
    try {
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

        while (uprs.next()) {
            float f = uprs.getFloat("PRICE");
            uprs.updateFloat("PRICE", f * percentage);
            uprs.updateRow();
        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:com.taobao.datax.plugins.writer.oraclejdbcwriter.OracleJdbcWriter.java

@Override
public int startWrite(LineReceiver receiver) {
    PreparedStatement ps = null;//  w  w  w.j  ava2s .  c o m
    try {
        this.connection = DBSource.getConnection(this.sourceUniqKey);

        this.logger.info(String.format("Config encoding %s .", this.encoding));

        /* load data begin */
        Line line = null;
        int lines = 0;
        if (StringUtils.isEmpty(this.insert)) {
            this.insert = this.buildInsertString();
        }
        logger.debug("sql=" + insert);
        ps = this.connection.prepareStatement(this.insert, ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        this.connection.setAutoCommit(false);
        while ((line = receiver.getFromReader()) != null) {
            try {
                for (int i = 0; i < line.getFieldNum(); i++) {
                    ps.setObject(i + 1, line.getField(i));
                }
                ps.execute();
            } catch (SQLException e) {
                if (e.getMessage().contains("ORA-00001")) {// unique
                    // constraint
                    // violated
                    logger.debug("Duplicated line found:" + line);
                    duplicatedLineBuffer.add(line);
                    if (this.duplicatedLineBuffer.size() >= this.duplicatedThreshold) {
                        logger.info("Too much duplicated lines,now process them .");
                        this.connection.commit();
                        this.flushDuplicatedBuffer();
                    }
                } else {
                    failCount++;
                    logger.debug("Fail line(" + e.getMessage() + "):" + line);
                    if (failCount >= this.limit) {
                        throw new DataExchangeException("Too many failed lines(" + failCount + ") .");
                    } else {
                        continue;
                    }
                }
            }
            if (lines++ == this.commitCount) {
                logger.info(lines + " committed by worker " + Thread.currentThread().getName() + " .");
                lines = 0;
                this.connection.commit();

            }
        }
        this.connection.commit();
        if (!this.duplicatedLineBuffer.isEmpty()) {
            logger.info("Some duplicated line will now be processed.");
            this.flushDuplicatedBuffer();
        }

        this.connection.setAutoCommit(true);
        this.getMonitor().setFailedLines(this.failCount);
        this.logger.info("DataX write to oracle ends by worker " + Thread.currentThread().getName() + " .");

        return PluginStatus.SUCCESS.value();
    } catch (Exception e2) {
        e2.printStackTrace();
        if (null != this.connection) {
            try {
                this.connection.close();
            } catch (SQLException e) {
            }
        }
        throw new DataExchangeException(e2.getCause());
    } finally {
        if (null != ps)
            try {
                ps.close();
            } catch (SQLException e3) {
            }
    }
}

From source file:gov.nih.nci.migration.MigrationDriver.java

private void encryptDecryptApplicationInformation() throws EncryptionException, SQLException {

    Connection connection = getConnection();
    Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

    ResultSet resultSet = null;/*from   w ww.j a  v a 2 s  .  c om*/
    if ("oracle".equals(DATABASE_TYPE)) {
        resultSet = stmt.executeQuery("SELECT CSM_APPLICATION.* FROM CSM_APPLICATION FOR UPDATE");
    } else {
        resultSet = stmt.executeQuery("SELECT * FROM CSM_APPLICATION");
    }

    String databasePassword = null;
    String encryptedDatabasePassword = null;

    while (resultSet.next()) {
        databasePassword = resultSet.getString("DATABASE_PASSWORD");

        if (!StringUtilities.isBlank(databasePassword)) {
            String orgPasswordStr = desEncryption.decrypt(databasePassword);
            encryptedDatabasePassword = aesEncryption.encrypt(orgPasswordStr);
            if (!StringUtilities.isBlank(encryptedDatabasePassword)) {
                resultSet.updateString("DATABASE_PASSWORD", encryptedDatabasePassword);
            }
        }
        System.out.println("Updating Application:" + resultSet.getString("APPLICATION_NAME"));
        resultSet.updateRow();
    }

}

From source file:com.bc.fiduceo.db.AbstractDriver.java

Sensor getSensor(int id) throws SQLException {
    final Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    final ResultSet resultSet = statement.executeQuery("SELECT * FROM SENSOR where ID = " + id);
    if (resultSet.next()) {
        final Sensor sensor = new Sensor();
        sensor.setName(resultSet.getString("Name"));
        return sensor;
    } else {/*from   ww w .  j av a 2 s .  com*/
        throw new SQLException("No Sensor available for ID '" + id + "'");
    }
}

From source file:org.opennms.provisiond.utils.CsvRequisitionParser.java

private static void migrateDbNodes() throws SQLException, UnknownHostException, ClassNotFoundException {

    String distinctNodesQueryStr = "  " + "SELECT nodeId AS \"nodeid\"," + "       nodeLabel AS \"nodelabel\","
            + "       foreignSource AS \"foreignsource\"," + "       foreignId AS \"foreignid\" "
            + "  FROM node " + " WHERE nodeid in (" + "  SELECT " + "DISTINCT nodeid " + "    FROM ipinterface "
            + "   WHERE iplike(ipaddr, '" + m_iplikeQuery + "')) " + "ORDER BY nodeid";

    if (m_addOnly) {
        distinctNodesQueryStr = "  " + "SELECT nodeId AS \"nodeid\"," + "       nodeLabel AS \"nodelabel\","
                + "       foreignSource AS \"foreignsource\"," + "       foreignId AS \"foreignid\" "
                + "  FROM node " + " WHERE nodeid in (" + "  SELECT " + "DISTINCT nodeid "
                + "    FROM ipinterface " + "   WHERE iplike(ipaddr, '" + m_iplikeQuery + "')) "
                + "  AND foreignsource is NULL " + "ORDER BY nodeid";
    }//from  w ww  . j  ava  2s .  co  m

    Connection connection = null;
    Statement distinctNodesStatement = null;
    PoolingConnection pool = null;
    connection = createConnection();
    connection.setAutoCommit(false);
    pool = new PoolingConnection(connection);
    distinctNodesStatement = pool.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

    ResultSet distinctNodesResultSet = null;
    int rowsFound = 0;
    distinctNodesResultSet = distinctNodesStatement.executeQuery(distinctNodesQueryStr);
    distinctNodesResultSet.last();
    rowsFound = distinctNodesResultSet.getRow();
    distinctNodesResultSet.beforeFirst();

    System.out.println(rowsFound + " nodes found.");

    int nodesMigrated = 0;
    while (distinctNodesResultSet.next()) {
        System.out.println("Processing row: " + distinctNodesResultSet.getRow() + "...");

        int nodeId = distinctNodesResultSet.getInt("nodeid");
        String queryStr = "" + "  SELECT ipaddr " + "    FROM ipinterface " + "   WHERE nodeid = " + nodeId
                + " " + "     AND issnmpprimary = 'P' " + "ORDER BY inet(ipaddr)" + "   LIMIT 1";

        Statement findPrimaryStatement = pool.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_READ_ONLY);

        System.out.println("Querying DB for SNMP Primary interface for node: " + nodeId + "...");
        ResultSet findPrimaryResultSet = findPrimaryStatement.executeQuery(queryStr);

        String primaryIp = null;

        if (findPrimaryResultSet.next()) {
            primaryIp = findPrimaryResultSet.getString("ipaddr");
            System.out.println("SNMP Primary found: " + primaryIp);
        }

        findPrimaryResultSet.close();
        findPrimaryStatement.close();

        if (primaryIp == null) {
            System.out.println("SNMP Primary not found.  Determining lowest numbered IP to set as Primary...");
            queryStr = "" + "  SELECT ipaddr " + "    FROM ipinterface " + "   WHERE nodeid = " + nodeId + " "
                    + "ORDER BY inet(ipaddr)" + "   LIMIT 1";
            findPrimaryStatement = pool.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            findPrimaryResultSet = findPrimaryStatement.executeQuery(queryStr);
        }

        if (primaryIp == null && findPrimaryResultSet.next()) {
            primaryIp = findPrimaryResultSet.getString("ipaddr");
            System.out.println("SNMP Primary found: " + primaryIp);
        }

        findPrimaryResultSet.close();
        findPrimaryStatement.close();

        if (primaryIp == null) {
            System.out.println(
                    "SNMP Primary not found.  Skipping node.  (This should never happen since it is the iplike query that finds the distinct nodes :( )");
            continue;
        }

        String foreignId = null;
        if (m_useNodeId) {
            foreignId = String.valueOf(nodeId);
        } else {
            foreignId = String.valueOf(System.currentTimeMillis());
        }

        String label = distinctNodesResultSet.getString("nodelabel");
        distinctNodesResultSet.updateString("foreignsource", m_foreignSource);
        distinctNodesResultSet.updateString("foreignId", foreignId);

        System.out.println("Updating node (" + nodeId + ":" + label + ") with foreignsource:" + m_foreignSource
                + " and foreignId:" + foreignId);
        distinctNodesResultSet.updateRow();
        System.out.println("Node updated.");

        RequisitionData rd = new RequisitionData(label, primaryIp, m_foreignSource, foreignId);

        if (m_categoryAddExisting) {
            String categoriesQueryString = "" + "SELECT c.categoryname as \"categoryname\" "
                    + "  FROM categories c " + "  JOIN category_node cn "
                    + "    ON cn.categoryid = c.categoryid " + "  JOIN node n on n.nodeid = cn.nodeid "
                    + " WHERE n.nodeid = " + nodeId;
            Statement categoriesStatement = pool.createStatement();

            ResultSet crs = categoriesStatement.executeQuery(categoriesQueryString);

            Set<String> categories = new LinkedHashSet<String>();
            while (crs.next()) {
                categories.add(crs.getString("categoryname"));
            }

            crs.close();
            categoriesStatement.close();
            rd.setCategories(categories);
        }

        System.out.println("Updating requistion...");
        createOrUpdateRequistion(rd);
        System.out.println("Requistion updated!  Next...\n");
        nodesMigrated++;
    }

    try {
        connection.commit();
    } catch (SQLException e) {
        e.printStackTrace();
        connection.rollback();
    }

    distinctNodesResultSet.close();
    distinctNodesStatement.close();
    pool.close();
    connection.close();

    System.out.println(nodesMigrated + " Nodes migrated to foreign source " + m_foreignSource);

}

From source file:com.itemanalysis.jmetrik.stats.transformation.LinearTransformationAnalysis.java

public String transformScore() throws SQLException {
    Statement stmt = null;//from   ww w  . j a  v a2  s .  com
    ResultSet rs = null;
    Double constrainedScore = null;

    try {
        //add variable to db
        dao.addColumnToDb(conn, tableName, addedVariableInfo);

        conn.setAutoCommit(false);//begin transaction

        Table sqlTable = new Table(tableName.getNameForDatabase());
        SelectQuery select = new SelectQuery();
        select.addColumn(sqlTable, selectedVariable.getName().nameForDatabase());
        select.addColumn(sqlTable, addedVariableInfo.getName().nameForDatabase());
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(select.toString());

        this.firePropertyChange("message", "", "Transforming scores...");

        double origValue = 0.0;
        double transValue = 0.0;
        double z = 0.0;

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

        while (rs.next()) {
            origValue = rs.getDouble(selectedVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                sd.increment(origValue);
                mean.increment(origValue);
                min.increment(origValue);
                max.increment(origValue);
            }
            updateProgress();
        }

        double meanValue = mean.getResult();
        double sdValue = sd.getResult();
        double minValue = min.getResult();
        double maxValue = max.getResult();
        double A = 1.0;
        double B = 0.0;

        rs.beforeFirst();

        while (rs.next()) {
            origValue = rs.getDouble(selectedVariable.getName().nameForDatabase());
            if (!rs.wasNull()) {
                if (type1) {
                    z = (origValue - meanValue) / sdValue;
                    transValue = scaleSd * z + scaleMean;
                    transValue = checkConstraints(transValue);
                } else {
                    A = (maxPossibleScore - minPossibleScore) / (maxValue - minValue);
                    B = minPossibleScore - minValue * A;
                    transValue = origValue * A + B;
                    transValue = checkConstraints(transValue);
                }

                descriptiveStatistics.increment(transValue);

                rs.updateDouble(addedVariableInfo.getName().nameForDatabase(), transValue);
                rs.updateRow();
            }
            updateProgress();
        }

        conn.commit();
        conn.setAutoCommit(true);

        //create output
        DefaultLinearTransformation linearTransformation = new DefaultLinearTransformation();
        linearTransformation.setScale(A);
        linearTransformation.setIntercept(B);

        StringBuilder sb = new StringBuilder();
        Formatter f = new Formatter(sb);
        f.format(publishHeader());
        f.format(descriptiveStatistics.toString());
        f.format(linearTransformation.toString());
        f.format("%n");
        f.format("%n");
        return f.toString();

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

}

From source file:com.bc.fiduceo.db.AbstractDriver.java

Integer getSensorId(String sensorName) throws SQLException {
    final Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    final ResultSet resultSet = statement
            .executeQuery("SELECT ID FROM SENSOR WHERE NAME = '" + sensorName + "'");

    if (resultSet.first()) {
        return resultSet.getInt("ID");
    } else {/*from  w w  w.  ja  v  a2  s.  c om*/
        return null;
    }
}

From source file:com.taobao.datax.plugins.writer.mysqlwriter.MysqlWriter.java

@Override
public int startWrite(LineReceiver receiver) {
    com.mysql.jdbc.Statement stmt = null;
    try {//from  w  w w  .  ja v a2 s .  c  om

        this.connection = DBSource.getConnection(this.sourceUniqKey);
        stmt = (com.mysql.jdbc.Statement) ((org.apache.commons.dbcp.DelegatingConnection) this.connection)
                .getInnermostDelegate()
                .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        /* set max count */
        this.logger.info(String.format("Config max_error_count: set max_error_count=%d", MAX_ERROR_COUNT));
        stmt.executeUpdate(String.format("set max_error_count=%d;", MAX_ERROR_COUNT));

        /* set connect encoding */
        this.logger.info(String.format("Config encoding %s .", this.encoding));
        for (String sql : this.makeLoadEncoding(encoding))
            stmt.execute(sql);

        /* load data begin */
        String loadSql = this.makeLoadSql();
        this.logger.info(String.format("Load sql: %s.", visualSql(loadSql)));

        MysqlWriterInputStreamAdapter localInputStream = new MysqlWriterInputStreamAdapter(receiver, this);
        stmt.setLocalInfileInputStream(localInputStream);
        stmt.executeUpdate(visualSql(loadSql));
        this.lineCounter = localInputStream.getLineNumber();

        this.logger.info("DataX write to mysql ends .");

        return PluginStatus.SUCCESS.value();
    } catch (Exception e2) {
        if (null != this.connection) {
            try {
                this.connection.close();
            } catch (SQLException e) {
            }
        }
        throw new DataExchangeException(e2.getCause());
    } finally {
        if (null != stmt)
            try {
                stmt.close();
            } catch (SQLException e3) {
            }
    }
}