List of usage examples for java.sql PreparedStatement getUpdateCount
int getUpdateCount() throws SQLException;
ResultSet
object or there are no more results, -1 is returned. From source file:com.l2jfree.gameserver.status.GameStatusThread.java
private void unjailOfflinePlayer(String name) { Connection con = null;//from ww w .j av a 2 s .c o m try { con = L2DatabaseFactory.getInstance().getConnection(con); PreparedStatement statement = con.prepareStatement( "UPDATE characters SET x=?, y=?, z=?, in_jail=?, jail_timer=? WHERE char_name=?"); statement.setInt(1, 17836); statement.setInt(2, 170178); statement.setInt(3, -3507); statement.setInt(4, 0); statement.setLong(5, 0); statement.setString(6, name); statement.execute(); int count = statement.getUpdateCount(); statement.close(); if (count == 0) _print.println("Character not found!"); else _print.println("Character " + name + " set free."); } catch (SQLException se) { _print.println("SQLException while jailing player"); if (_log.isDebugEnabled()) _log.warn("SQLException while jailing player", se); } finally { L2DatabaseFactory.close(con); } }
From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java
/** * Internal update methods/*www . j a v a 2s .co m*/ * These are helpers for the rest of the interface */ private int getUpdateCount(PreparedStatement preparedStatement) { try { return preparedStatement.getUpdateCount(); } catch (SQLException e) { throw new UnsuccessfulOperationError("Failed to retrieve the number of affected rows", e); } }
From source file:com.l2jfree.gameserver.status.GameStatusThread.java
private void jailOfflinePlayer(String name, int delay) { Connection con = null;//w w w . j a v a 2s.co m try { con = L2DatabaseFactory.getInstance().getConnection(con); PreparedStatement statement = con.prepareStatement( "UPDATE characters SET x=?, y=?, z=?, in_jail=?, jail_timer=? WHERE char_name=?"); statement.setInt(1, L2JailZone.JAIL_LOCATION.getX()); statement.setInt(2, L2JailZone.JAIL_LOCATION.getY()); statement.setInt(3, L2JailZone.JAIL_LOCATION.getZ()); statement.setInt(4, 1); statement.setLong(5, delay * 60000L); statement.setString(6, name); statement.execute(); int count = statement.getUpdateCount(); statement.close(); if (count == 0) _print.println("Character not found!"); else _print.println("Character " + name + " jailed for " + (delay > 0 ? delay + " minutes." : "ever!")); } catch (SQLException se) { _print.println("SQLException while jailing player"); if (_log.isDebugEnabled()) _log.warn("SQLException while jailing player", se); } finally { L2DatabaseFactory.close(con); } }
From source file:org.apache.cayenne.access.jdbc.SQLTemplateAction.java
protected void execute(Connection connection, OperationObserver callback, SQLStatement compiled, Collection<Number> updateCounts) throws SQLException, Exception { long t1 = System.currentTimeMillis(); boolean iteratedResult = callback.isIteratedResult(); PreparedStatement statement = connection.prepareStatement(compiled.getSql()); try {//from w w w .j av a2s . c o m bind(statement, compiled.getBindings()); // process a mix of results boolean isResultSet = statement.execute(); boolean firstIteration = true; while (true) { if (firstIteration) { firstIteration = false; } else { isResultSet = statement.getMoreResults(); } if (isResultSet) { ResultSet resultSet = statement.getResultSet(); if (resultSet != null) { try { processSelectResult(compiled, connection, statement, resultSet, callback, t1); } finally { if (!iteratedResult) { resultSet.close(); } } // ignore possible following update counts and bail early on iterated results if (iteratedResult) { break; } } } else { int updateCount = statement.getUpdateCount(); if (updateCount == -1) { break; } updateCounts.add(updateCount); dataNode.getJdbcEventLogger().logUpdateCount(updateCount); } } } finally { if (!iteratedResult) { statement.close(); } } }
From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java
@Override public <E> E update(E entity) { final Map<Object, Object> saveQueue = this.saveQueue.get(); if (saveQueue.containsKey(entity)) { //noinspection unchecked return (E) saveQueue.get(entity); }/*from w w w .j a va 2s .c o m*/ saveQueueLock.set(saveQueueLock.get() + 1); final EntityHandler<E> entityHandler = entityHandlerContext.getHandler(entity); final E enhancedEntity = getEnhancedEntity(entity); if (entityHandler.hasKey() && entityHandler.getKey(enhancedEntity) != null) { initializationContext.delete(entityHandler.getEntityType(), entityHandler.getKey(enhancedEntity)); } saveQueue.put(entity, enhancedEntity); final InitializedEntity<E> initializedEntity = getInitializedEntity(enhancedEntity); entityHandler.saveDependencyRelations(enhancedEntity, this); eventHandler.beforeUpdate(enhancedEntity); final Map<String, Object> current = entityHandler.toMap(enhancedEntity); final Map<String, Object> values = new HashMap<String, Object>(); values.putAll(MapTools.prefixKeys(current, "value.")); values.putAll(MapTools.prefixKeys(current, "new.")); if (initializedEntity.getOriginalCopy() == null) { initializedEntity.setOriginalCopy(enhancedEntity); } final E originalCopy = initializedEntity.getOriginalCopy(); initializedEntity.freeze(); final Map<String, Object> original = entityHandler.toMap(originalCopy); values.putAll(MapTools.prefixKeys(original, "old.")); for (String key : original.keySet()) { if (!values.containsKey("value." + key)) { values.put("value." + key, original.get(key)); } } final PreparedStatement preparedStatement = internalExecuteUpdate(entityHandler.getEntityType(), Statements.Manipulation.UPDATE, values); try { final boolean updated = preparedStatement.getUpdateCount() > 0; if (entityHandler.isLockable() && !updated) { throw new OptimisticLockingFailureError(entityHandler.getEntityType()); } entityHandler.incrementVersion(enhancedEntity); eventHandler.afterUpdate(enhancedEntity, updated); } catch (SQLException e) { throw new UnsuccessfulOperationError("Failed to count the number of updated elements", e); } cleanUpStatement(preparedStatement); saveDependents(entityHandler, enhancedEntity); saveQueueLock.set(saveQueueLock.get() - 1); if (saveQueueLock.get() == 0) { saveQueue.remove(entity); for (Object object : deferredSaveQueue.get()) { saveQueue.remove(object); } deferredSaveQueue.get().clear(); } else { deferredSaveQueue.get().add(entity); } entityHandler.copy(enhancedEntity, entity); if (entityHandler.hasKey() && entityHandler.getKey(enhancedEntity) != null) { initializationContext.register(entityHandler.getEntityType(), entityHandler.getKey(enhancedEntity), enhancedEntity); } initializedEntity.unfreeze(); return enhancedEntity; }
From source file:com.chiorichan.database.DatabaseEngine.java
public int queryUpdate(String query, Object... args) throws SQLException { PreparedStatement stmt = null; if (con == null) throw new SQLException("The SQL connection is closed or was never opened."); try {/* ww w . j av a 2s. c o m*/ stmt = con.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); int x = 0; for (Object s : args) try { x++; stmt.setString(x, ObjectUtil.castToString(s)); } catch (SQLException e) { if (!e.getMessage().startsWith("Parameter index out of range")) throw e; } stmt.execute(); Loader.getLogger().fine("Update Query: \"" + stmt.toString() + "\" which affected " + stmt.getUpdateCount() + " row(s)."); } catch (MySQLNonTransientConnectionException e) { if (reconnect()) return queryUpdate(query); } catch (CommunicationsException e) { if (reconnect()) return queryUpdate(query); } catch (Exception e) { e.printStackTrace(); } return stmt.getUpdateCount(); }
From source file:kenh.xscript.database.elements.Execute.java
/** * Execute sql.//from ww w . j a va 2s . co m * @param sql * @param parameter * @param var variable name of result * @param conn */ private int executeSQL(SQLBean sqlBean, String var, java.sql.Connection conn) throws UnsupportedScriptException { if (sqlBean == null || StringUtils.isBlank(sqlBean.getSql())) { UnsupportedScriptException ex = new UnsupportedScriptException(this, "Can't find the sql to execute."); throw ex; } if (conn == null) { throw new UnsupportedScriptException(this, "Connection is empty."); } var = StringUtils.trimToNull(var); PreparedStatement pstmt = null; ResultSet rs = null; try { if (conn.isClosed()) { throw new UnsupportedScriptException(this, "Connection is closed."); } StringBuffer traceInfo = new StringBuffer(); traceInfo.append("Execute SQL: \n" + StringUtils.trim(sqlBean.getSql())); pstmt = conn.prepareStatement(sqlBean.getSql()); Map<String, String> parameters = getParameters(sqlBean); Iterator<String> elements = parameters.values().iterator(); // set the Paramter for PreparedStatement int i = 1; while (elements.hasNext()) { String str = elements.next(); Object obj = this.getEnvironment().parse(str); traceInfo.append("\nParam " + i + ": " + obj.toString()); pstmt.setObject(i, obj); i++; } logger.trace(traceInfo.toString()); boolean result = false; result = pstmt.execute(); if (result) { rs = pstmt.getResultSet(); if (StringUtils.isNotBlank(var)) { ResultSetBean bean = new ResultSetBean(rs); this.saveVariable(var, bean, null); } } else { int count = pstmt.getUpdateCount(); if (StringUtils.isNotBlank(var)) this.saveVariable(var, count, null); } } catch (java.sql.SQLException | IllegalAccessException | InstantiationException e) { this.getEnvironment().setVariable(Constant.VARIABLE_EXCEPTION, e); return EXCEPTION; } catch (UnsupportedExpressionException e) { throw new UnsupportedScriptException(this, e); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { } rs = null; } if (pstmt != null) { try { pstmt.close(); } catch (Exception e) { } pstmt = null; } } return NONE; }
From source file:org.apache.beehive.controls.system.jdbc.JdbcControlImpl.java
/** * Create and exec a {@link PreparedStatement} * * @param method the method to invoke//from w w w . j ava 2 s . c o m * @param args the method's arguments * @return the return value from the {@link PreparedStatement} * @throws Throwable any exception that occurs; the caller should handle these appropriately */ protected Object execPreparedStatement(Method method, Object[] args) throws Throwable { final SQL methodSQL = (SQL) _context.getMethodPropertySet(method, SQL.class); if (methodSQL == null || methodSQL.statement() == null) { throw new ControlException("Method " + method.getName() + " is missing @SQL annotation"); } setTypeMappers(methodSQL.typeMappersOverride()); // // build the statement and execute it // PreparedStatement ps = null; try { Class returnType = method.getReturnType(); SqlStatement sqlStatement = _sqlParser.parse(methodSQL.statement()); ps = sqlStatement.createPreparedStatement(_context, _connection, _cal, method, args); if (LOGGER.isInfoEnabled()) { LOGGER.info("PreparedStatement: " + sqlStatement.createPreparedStatementString(_context, _connection, method, args)); } // // special processing for batch updates // if (sqlStatement.isBatchUpdate()) { return ps.executeBatch(); } // // execute the statement // boolean hasResults = ps.execute(); // // callable statement processing // if (sqlStatement.isCallableStatement()) { SQLParameter[] params = (SQLParameter[]) args[0]; for (int i = 0; i < params.length; i++) { if (params[i].dir != SQLParameter.IN) { params[i].value = ((CallableStatement) ps).getObject(i + 1); } } return null; } // // process returned data // ResultSet rs = null; int updateCount = ps.getUpdateCount(); if (hasResults) { rs = ps.getResultSet(); } if (sqlStatement.getsGeneratedKeys()) { rs = ps.getGeneratedKeys(); hasResults = true; } if (!hasResults && updateCount > -1) { boolean moreResults = ps.getMoreResults(); int tempUpdateCount = ps.getUpdateCount(); while ((moreResults && rs == null) || tempUpdateCount > -1) { if (moreResults) { rs = ps.getResultSet(); hasResults = true; moreResults = false; tempUpdateCount = -1; } else { moreResults = ps.getMoreResults(); tempUpdateCount = ps.getUpdateCount(); } } } Object returnObject = null; if (hasResults) { // // if a result set mapper was specified in the methods annotation, use it // otherwise find the mapper for the return type in the hashmap // final Class resultSetMapperClass = methodSQL.resultSetMapper(); final ResultSetMapper rsm; if (!UndefinedResultSetMapper.class.isAssignableFrom(resultSetMapperClass)) { if (ResultSetMapper.class.isAssignableFrom(resultSetMapperClass)) { rsm = (ResultSetMapper) resultSetMapperClass.newInstance(); } else { throw new ControlException( "Result set mappers must be subclasses of ResultSetMapper.class!"); } } else { if (_resultMappers.containsKey(returnType)) { rsm = _resultMappers.get(returnType); } else { if (_xmlObjectClass != null && _xmlObjectClass.isAssignableFrom(returnType)) { rsm = _resultMappers.get(_xmlObjectClass); } else { rsm = DEFAULT_MAPPER; } } } returnObject = rsm.mapToResultType(_context, method, rs, _cal); if (rsm.canCloseResultSet() == false) { getResources().add(ps); } // // empty ResultSet // } else { if (returnType.equals(Void.TYPE)) { returnObject = null; } else if (returnType.equals(Integer.TYPE)) { returnObject = new Integer(updateCount); } else if (!sqlStatement.isCallableStatement()) { throw new ControlException( "Method " + method.getName() + "is DML but does not return void or int"); } } return returnObject; } finally { // Keep statements open that have in-use result sets if (ps != null && !getResources().contains(ps)) { ps.close(); } } }
From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java
@Override public boolean deleteEntityInTable(String tableName, ODataEntry entry) throws ODataServiceFault { List<String> pKeys = this.primaryKeys.get(tableName); Connection connection = null; PreparedStatement statement = null; String value;// w w w . ja v a 2s . c o m try { connection = initializeConnection(); String query = createDeleteSQL(tableName); statement = connection.prepareStatement(query); int index = 1; for (String column : this.rdbmsDataTypes.get(tableName).keySet()) { if (pKeys.contains(column)) { value = entry.getValue(column); bindValuesToPreparedStatement(this.rdbmsDataTypes.get(tableName).get(column), value, index, statement); index++; } } statement.execute(); int rowCount = statement.getUpdateCount(); commitExecution(connection); return rowCount > 0; } catch (SQLException | ParseException e) { throw new ODataServiceFault(e, "Error occurred while deleting the entity from " + tableName + " table. :" + e.getMessage()); } finally { releaseResources(null, statement); releaseConnection(connection); } }
From source file:org.opoo.oqs.core.AbstractQuery.java
/** * ResultSetID//w w w . ja v a 2 s . co m * * @param sql String * @return Serializable */ private Serializable getInsertSelectIdentity(String sql) { try { ConnectionManager manager = queryFactory.getConnectionManager(); Connection conn = queryFactory.getConnectionManager().getConnection(); PreparedStatement ps = conn.prepareStatement(sql); try { Object values[] = valueArray(); for (int i = 0; i < values.length; i++) { Object value = values[i]; if (value == null) { Type.SERIALIZABLE.safeSet(ps, value, i + 1); } else { TypeFactory.guessType(value).safeSet(ps, value, i + 1); } } if (dialect.supportsInsertSelectIdentity()) { if (!ps.execute()) { while (!ps.getMoreResults() && ps.getUpdateCount() != -1) { continue; // Do nothing (but stop checkstyle from complaining). } } //note early exit! ResultSet rs = ps.getResultSet(); try { return getGeneratedIdentity(rs); } finally { //JdbcUtils.closeResultSet(rs); close(rs, null); } } //else if (Settings.isGetGeneratedKeysEnabled()) //{ // ps.executeUpdate(); // //note early exit! // return getGeneratedIdentity(ps.getGeneratedKeys()); //} //else //{ // ps.executeUpdate(); //need post insert then select identity //postInsert.append("NEED"); //} //else if else else { ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); if (rs != null) { //getGeneratedKeys()key try { log.debug("Using getGeneratedKeys() to get keys."); return getGeneratedIdentity(rs); } finally { close(rs, null); } } //elsegetPostInsertGeneratedIndentity } } finally { //JdbcUtils.closeStatement(ps); close(null, ps); //JdbcUtils.closeConnection(conn); //PostInsertGeneratedIndentiry manager.releaseConnection(conn); } } catch (SQLException ex) { //throw new QueryException("could not insert: ", ex); log.debug("could not get id for insert, using getPostInsertGeneratedIndentity(): " + ex.getMessage()); } return getPostInsertGeneratedIndentity(); }