Example usage for java.sql PreparedStatement getUpdateCount

List of usage examples for java.sql PreparedStatement getUpdateCount

Introduction

In this page you can find the example usage for java.sql PreparedStatement getUpdateCount.

Prototype

int getUpdateCount() throws SQLException;

Source Link

Document

Retrieves the current result as an update count; if the result is a ResultSet object or there are no more results, -1 is returned.

Usage

From source file:com.flexive.core.storage.MySQL.MySQLSequencerStorage.java

/**
 * {@inheritDoc}//from   ww w  . ja  v a2  s. c  om
 */
@Override
public void createSequencer(String name, boolean allowRollover, long startNumber)
        throws FxApplicationException {
    if (StringUtils.isEmpty(name) || name.toUpperCase().trim().startsWith("SYS_"))
        throw new FxCreateException(LOG, "ex.sequencer.create.invalid.name", name);
    name = name.toUpperCase().trim();
    if (sequencerExists(name))
        throw new FxCreateException(LOG, "ex.sequencer.create.invalid.name", name);

    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = Database.getDbConnection();

        ps = con.prepareStatement(SQL_CREATE);
        ps.setLong(1, startNumber);
        ps.setString(2, name);
        ps.setBoolean(3, allowRollover);
        ps.executeUpdate();
        if (ps.getUpdateCount() == 0)
            throw new FxCreateException(LOG, "ex.sequencer.create.failed", name);
    } catch (SQLException exc) {
        throw new FxCreateException(LOG, exc, "ex.sequencer.create.failed", name);
    } finally {
        Database.closeObjects(MySQLSequencerStorage.class, con, ps);
    }
}

From source file:com.flexive.core.storage.MySQL.MySQLSequencerStorage.java

/**
 * {@inheritDoc}//from   w ww  .  ja  va  2  s  . com
 */
@Override
public long fetchId(String name, boolean allowRollover) throws FxCreateException {
    Connection con = null;
    PreparedStatement ps = null;
    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        // Prepare the new id
        ps = con.prepareStatement(SQL_NEXT);
        ps.setString(1, name);
        ps.executeUpdate();
        if (ps.getUpdateCount() == 0)
            throw new FxCreateException(LOG, "ex.sequencer.typeUnknown", name);
        ps.close();

        // Get the new id
        ps = con.prepareStatement(SQL_GETID);
        ResultSet rs = ps.executeQuery();
        long newId;
        if (rs == null || !rs.next())
            throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
        newId = rs.getLong(1);
        if (rs.wasNull())
            throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
        if (newId >= MAX_ID) {
            if (!name.startsWith("SYS_")) {
                //get allowRollover setting
                ps.close();
                ps = con.prepareStatement(SQL_GET_ROLLOVER);
                ps.setString(1, name);
                ResultSet rso = ps.executeQuery();
                if (rso == null || !rso.next())
                    throw new FxCreateException(LOG, "ex.sequencer.fetch.failed", name);
                allowRollover = rso.getBoolean(1);
            }
            if (!allowRollover)
                throw new FxCreateException("ex.sequencer.exhausted", name);
            ps.close();
            ps = con.prepareStatement(SQL_RESET);
            ps.setString(1, name);
            ps.executeUpdate();
            if (ps.getUpdateCount() == 0)
                throw new FxCreateException(LOG, "ex.sequencer.typeUnknown", name);
            newId = 0;
        }
        // Return new id
        return newId;
    } catch (SQLException exc) {
        throw new FxCreateException(LOG, exc, "ex.sequencer.fetch.failedMsg", name, exc.getMessage());
    } finally {
        Database.closeObjects(MySQLSequencerStorage.class, con, ps);
    }
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method updates the variable "isActive" in the database. The variable
 * "isActive" is a column of the table "OutputDevices". With this method the
 * output devices can notify if they are active and like to get messages or
 * not./*from  w w  w  .j  a  v  a  2  s  . c  om*/
 * 
 * @param classes
 *            class of the output device
 * @param name
 *            name of the output device
 * @param active
 *            true= is active and like to get messages false=is not active
 *            and does not listen to messages
 */
@GET
@Path("/isActive/{classes}/{name}/{isActive}")
public synchronized static String isActive(@PathParam("classes") String classes, @PathParam("name") String name,
        @PathParam("isActive") String active) {
    createDBConnection();
    String ok = "ok";
    PreparedStatement st;
    try {
        boolean isActive = false;

        if (active.equals("t")) {
            isActive = true;
        }
        st = conn.prepareStatement("update \"OutputDevices\" set enabled=? where \"class\"=? and \"topic\"=?;");
        st.setBoolean(1, isActive);
        st.setString(2, classes);
        st.setString(3, name);
        st.execute();
        if (st.getUpdateCount() != 1) {
            ok = "class or topic not found";
        } else {
            deviceActive.put(classes + "," + name, isActive);
        }
    } catch (SQLException e) {
        logger.error("SQL Exception in Method isActive", e);
    }
    closeDBConnection();
    return ok;
}

From source file:org.biokoframework.system.repository.sql.SqlRepository.java

@Override
public DE delete(String anEntityKey) {
    DE toBeDeleted = retrieve(anEntityKey);
    boolean deleted = false;

    Connection connection = null;
    PreparedStatement deleteStatement = null;
    try {//from  w w  w  .  j  a v  a2 s .  co m
        connection = fDbConnector.getConnection();
        deleteStatement = SqlStatementsHelper.preparedDeleteByIdStatement(fEntityClass, fTableName, connection);
        deleteStatement.setString(1, anEntityKey);
        deleteStatement.execute();

        deleted = deleteStatement.getUpdateCount() > 0;
        deleteStatement.close();
        connection.close();
    } catch (SQLException exception) {
        closeDumbSql(connection, deleteStatement, null);
        exception.printStackTrace();
    }

    if (deleted) {
        return toBeDeleted;
    } else {
        return null;
    }
}

From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCwoTimeOutTestElement.java

private String resultSetsToString(final PreparedStatement pstmt, boolean result, final int[] out)
        throws SQLException, UnsupportedEncodingException {
    final StringBuilder sb = new StringBuilder();
    int updateCount = 0;
    if (!result) {
        updateCount = pstmt.getUpdateCount();
    }//w  ww .  j  a  v  a 2s .  c  om
    do {
        if (result) {
            ResultSet rs = null;
            try {
                rs = pstmt.getResultSet();
                sb.append(getStringFromResultSet(rs)).append("\n"); // $NON-NLS-1$
            } finally {
                close(rs);
            }
        } else {
            sb.append(updateCount).append(" updates.\n");
        }
        result = pstmt.getMoreResults();
        if (!result) {
            updateCount = pstmt.getUpdateCount();
        }
    } while (result || (updateCount != -1));
    if (out != null && pstmt instanceof CallableStatement) {
        final ArrayList<Object> outputValues = new ArrayList<Object>();
        final CallableStatement cs = (CallableStatement) pstmt;
        sb.append("Output variables by position:\n");
        for (int i = 0; i < out.length; i++) {
            if (out[i] != java.sql.Types.NULL) {
                final Object o = cs.getObject(i + 1);
                outputValues.add(o);
                sb.append("[");
                sb.append(i + 1);
                sb.append("] ");
                sb.append(o);
                sb.append("\n");
            }
        }
        final String varnames[] = getVariableNames().split(COMMA);
        if (varnames.length > 0) {
            final JMeterVariables jmvars = getThreadContext().getVariables();
            for (int i = 0; i < varnames.length && i < outputValues.size(); i++) {
                final String name = varnames[i].trim();
                if (name.length() > 0) { // Save the value in the variable if present
                    final Object o = outputValues.get(i);
                    jmvars.put(name, o == null ? null : o.toString());
                }
            }
        }
    }
    return sb.toString();
}

From source file:com.nextep.designer.sqlclient.ui.services.impl.SQLClientService.java

@Override
public void deleteQueryValue(ISQLQuery query, ISQLRowResult row) throws SQLException {
    ISQLRowModificationStatus status = computeRowModificationStatus(query, row, -1);
    if (status.isModifiable()) {
        final ISQLResult result = query.getResult();
        final Connection conn = query.getConnection();
        final DatabaseMetaData md = conn.getMetaData();
        final String deleteStmt = buildDeleteStatement(status, md.getIdentifierQuoteString());
        PreparedStatement stmt = null;
        try {/*from ww  w  .j a v  a2  s  .  c o m*/
            stmt = conn.prepareStatement(deleteStmt);
            fillPreparedStatement(stmt, false, false, row, null);
            stmt.execute();
            if (stmt.getUpdateCount() > 0) {
                result.removeRow(row);
            }
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }

    }

}

From source file:org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler.java

private String resultSetsToString(PreparedStatement pstmt, boolean result, int[] out)
        throws SQLException, UnsupportedEncodingException {
    StrBuilder sb = new StrBuilder();
    int updateCount = 0;
    if (!result) {
        updateCount = pstmt.getUpdateCount();
    }/*  w  ww  . ja  v a 2 s. c  o  m*/
    do {
        if (result) {
            ResultSet rs = null;
            try {
                rs = pstmt.getResultSet();
                sb.append(getStringFromResultSet(rs)).append("\n"); // $NON-NLS-1$
            } finally {
                close(rs);
            }
        } else {
            sb.append(updateCount).append(" updates.\n");
        }
        result = pstmt.getMoreResults();
        if (!result) {
            updateCount = pstmt.getUpdateCount();
        }
    } while (result || (updateCount != -1));
    if (out != null && pstmt instanceof CallableStatement) {
        CallableStatement cs = (CallableStatement) pstmt;
        sb.append("Output variables by position:\n");
        for (int i = 0; i < out.length; i++) {
            if (out[i] != java.sql.Types.NULL) {
                sb.append("[");
                sb.append(i + 1);
                sb.append("] ");
                sb.append(cs.getObject(i + 1));
                sb.append("\n");
            }
        }
    }
    return sb.toString();
}

From source file:com.cloudera.sqoop.tool.EvalSqlTool.java

@Override
/** {@inheritDoc} */
public int run(SqoopOptions options) {
    if (!init(options)) {
        return 1;
    }//  w w  w  .j  av a  2 s  .c om

    PreparedStatement stmt = null;
    ResultSet rs = null;
    PrintWriter pw = null;
    try {
        Connection c = manager.getConnection();
        String query = options.getSqlQuery();
        LOG.debug("SQL query: " + query);
        stmt = c.prepareStatement(query);
        boolean resultType = stmt.execute();
        // Iterate over all the results from this statement.
        while (true) {
            LOG.debug("resultType=" + resultType);
            if (!resultType) {
                // This result was an update count.
                int updateCount = stmt.getUpdateCount();
                LOG.debug("updateCount=" + updateCount);
                if (updateCount == -1) {
                    // We are done iterating over results from this statement.
                    c.commit();
                    break;
                } else {
                    LOG.info(updateCount + " row(s) updated.");
                }
            } else {
                // This yields a ResultSet.
                rs = stmt.getResultSet();
                pw = new PrintWriter(System.out, true);
                new ResultSetPrinter().printResultSet(pw, rs);
                pw.close();
                pw = null;
            }

            resultType = stmt.getMoreResults();
        }
    } catch (IOException ioe) {
        LOG.warn("IOException formatting results: " + StringUtils.stringifyException(ioe));
        return 1;
    } catch (SQLException sqlE) {
        LOG.warn("SQL exception executing statement: " + StringUtils.stringifyException(sqlE));
        return 1;
    } finally {
        if (null != pw) {
            pw.close();
        }
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException sqlE) {
                LOG.warn("SQL exception closing ResultSet: " + StringUtils.stringifyException(sqlE));
            }
        }
        if (null != stmt) {
            try {
                stmt.close();
            } catch (SQLException sqlE) {
                LOG.warn("SQL exception closing statement: " + StringUtils.stringifyException(sqlE));
            }
        }
        destroy(options);
    }

    return 0;
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

/**
 * Delete an entry./*from w ww.j  a  v  a2 s.c om*/
 * 
 * @param connection
 *        The connection
 * @param key
 *        The key
 * @throws SQLException
 */
private void delete(Connection connection, String key) throws SQLException {
    Lock lock = lockSource.getWriteLock(key);
    lock.lock();
    try {
        String sql = "DELETE FROM " + cacheTableName + " WHERE key=?";
        PreparedStatement statement = connection.prepareStatement(sql);
        try {
            statement.setString(1, key);
            if (!statement.execute()) {
                if (logger.isLoggable(Level.FINE) && statement.getUpdateCount() > 0)
                    logger.fine("Deleted: " + key);
            }
        } finally {
            statement.close();
        }
    } finally {
        lock.unlock();
        lockSource.discard(key);
    }
}

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

/**
 * Persist a domain object, without using auto-generated keys.
 * //w  w w.ja va2 s  . c om
 * @param obj
 *        the domain object to persist
 * @param sqlInsert
 *        the SQL insert statement to use
 * @return the primary key created for the domain object
 */
protected Long storeDomainObjectWithoutAutogeneratedKeys(final T obj, final String sqlInsert) {
    Object result = getJdbcTemplate().execute(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(sqlInsert);
            setStoreStatementValues(obj, ps);
            return ps;
        }
    }, new PreparedStatementCallback<Object>() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();
            int count = ps.getUpdateCount();
            if (count == 1 && ps.getMoreResults()) {
                ResultSet rs = ps.getResultSet();
                if (rs.next()) {
                    return rs.getObject(1);
                }
            }
            return null;
        }
    });
    if (result instanceof Long) {
        return (Long) result;
    } else if (result instanceof Number) {
        return Long.valueOf(((Number) result).longValue());
    }
    if (log.isWarnEnabled()) {
        log.warn("Unexpected (non-number) primary key returned: " + result);
    }
    return null;
}