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:org.jumpmind.db.sql.JdbcSqlTransaction.java
public int prepareAndExecute(final String sql, final Object... args) { return executeCallback(new IConnectionCallback<Integer>() { public Integer execute(Connection con) throws SQLException { PreparedStatement stmt = null; ResultSet rs = null;//w w w . j a v a2 s. c o m try { logSql(sql, args); stmt = con.prepareStatement(sql); if (args != null && args.length > 0) { jdbcSqlTemplate.setValues(stmt, args); } if (stmt.execute()) { rs = stmt.getResultSet(); while (rs.next()) { } } return stmt.getUpdateCount(); } finally { JdbcSqlTemplate.close(rs); JdbcSqlTemplate.close(stmt); } } }); }
From source file:com.threecrickets.prudence.cache.SqlCache.java
public void prune() { // Note that this will not discard locks try {/*from www . j a va 2s.co m*/ Connection connection = connect(); if (connection == null) return; try { String sql = "DELETE FROM " + cacheTableName + " WHERE expiration_date<?"; PreparedStatement statement = connection.prepareStatement(sql); try { statement.setTimestamp(1, new Timestamp(System.currentTimeMillis())); if (!statement.execute()) logger.fine("Pruned " + statement.getUpdateCount()); } finally { statement.close(); } } finally { connection.close(); } } catch (SQLException x) { logger.log(Level.WARNING, "Could not prune", x); } }
From source file:org.jumpmind.db.sql.JdbcSqlTransaction.java
public int prepareAndExecute(final String sql, final Object[] args, final int[] types) { return executeCallback(new IConnectionCallback<Integer>() { public Integer execute(Connection con) throws SQLException { PreparedStatement stmt = null; ResultSet rs = null;//from www. java 2 s . c o m try { logSql(sql, args); stmt = con.prepareStatement(sql); jdbcSqlTemplate.setValues(stmt, args, types, jdbcSqlTemplate.getLobHandler().getDefaultHandler()); if (stmt.execute()) { rs = stmt.getResultSet(); while (rs.next()) { } } return stmt.getUpdateCount(); } finally { JdbcSqlTemplate.close(rs); JdbcSqlTemplate.close(stmt); } } }); }
From source file:com.mirth.connect.server.userutil.DatabaseConnection.java
/** * Executes a prepared INSERT/UPDATE statement on the database and returns the row count. * //from w w w .j ava 2 s .c o m * @param expression * The prepared statement to be executed. * @param parameters * The parameters for the prepared statement. * @return A count of the number of updated rows. * @throws SQLException */ public int executeUpdate(String expression, List<Object> parameters) throws SQLException { PreparedStatement statement = null; try { statement = connection.prepareStatement(expression); logger.debug("executing prepared statement:\n" + expression); ListIterator<Object> iterator = parameters.listIterator(); while (iterator.hasNext()) { int index = iterator.nextIndex() + 1; Object value = iterator.next(); logger.debug("adding parameter: index=" + index + ", value=" + value); statement.setObject(index, value); } if (statement.execute()) { return -1; } else { return statement.getUpdateCount(); } } catch (SQLException e) { throw e; } finally { DbUtils.closeQuietly(statement); } }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
private String resultSetsToString(PreparedStatement pstmt, boolean result, int[] out) throws SQLException, UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); int updateCount = 0; if (!result) { updateCount = pstmt.getUpdateCount(); }/* w ww. j a 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) { List<Object> outputValues = new ArrayList<>(); 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) { Object o = cs.getObject(i + 1); outputValues.add(o); sb.append("["); sb.append(i + 1); sb.append("] "); sb.append(o); if (o instanceof java.sql.ResultSet && RS_COUNT_RECORDS.equals(resultSetHandler)) { sb.append(" ").append(countRows((ResultSet) o)).append(" rows"); } sb.append("\n"); } } String[] varnames = getVariableNames().split(COMMA); if (varnames.length > 0) { JMeterVariables jmvars = getThreadContext().getVariables(); for (int i = 0; i < varnames.length && i < outputValues.size(); i++) { String name = varnames[i].trim(); if (name.length() > 0) { // Save the value in the variable if present Object o = outputValues.get(i); if (o instanceof java.sql.ResultSet) { ResultSet resultSet = (ResultSet) o; if (RS_STORE_AS_OBJECT.equals(resultSetHandler)) { jmvars.putObject(name, o); } else if (RS_COUNT_RECORDS.equals(resultSetHandler)) { jmvars.put(name, o.toString() + " " + countRows(resultSet) + " rows"); } else { jmvars.put(name, o.toString()); } } else { jmvars.put(name, o == null ? null : o.toString()); } } } } } return sb.toString(); }
From source file:org.wso2.carbon.appfactory.core.dao.JDBCResourceDAO.java
/** * Delete a resource/*from w ww . jav a2 s . com*/ * * @param applicationKey application key * @param resourceName resource name * @param resourceType resource type * @param environment environment * @return true if resources deleted successfully * @throws AppFactoryException */ public boolean deleteResource(String applicationKey, String resourceName, String resourceType, String environment) throws AppFactoryException { Connection databaseConnection = null; PreparedStatement preparedStatement = null; try { databaseConnection = AppFactoryDBUtil.getConnection(); preparedStatement = databaseConnection.prepareStatement(SQLConstants.DELETE_RESOURCE_SQL); int applicationId = JDBCApplicationDAO.getInstance().getAutoIncrementAppID(applicationKey, databaseConnection); preparedStatement.setInt(1, applicationId); preparedStatement.setString(2, resourceName); preparedStatement.setString(3, resourceType); preparedStatement.setString(4, environment); preparedStatement.execute(); int affectedRow = preparedStatement.getUpdateCount(); if (affectedRow > 0) { databaseConnection.commit(); JDBCResourceCacheManager.clearCache(applicationKey, environment, resourceType); if (log.isDebugEnabled()) { log.debug("Cache cleared for resource type : " + resourceType + " of application : " + applicationKey + " in : " + environment); } return true; } } catch (SQLException e) { try { if (databaseConnection != null) { databaseConnection.rollback(); } } catch (SQLException e1) { String msg = "Error while rolling back resource deletion for : " + resourceName + " of resource type : " + resourceType + " of application : " + applicationKey + " in : " + environment; log.error(msg, e1); } String msg = "Error while deleting resource : " + resourceName + " of resource type : " + resourceType + " of application : " + applicationKey + " in : " + environment; log.error(msg, e); throw new AppFactoryException(msg, e); } finally { AppFactoryDBUtil.closePreparedStatement(preparedStatement); AppFactoryDBUtil.closeConnection(databaseConnection); } return false; }
From source file:com.threecrickets.prudence.cache.SqlCache.java
public void invalidate(String tag) { try {/*from www . j av a2 s .co m*/ Connection connection = connect(); if (connection == null) return; try { List<String> tagged = getTagged(connection, tag); if (tagged.isEmpty()) return; ArrayList<Lock> locks = new ArrayList<Lock>(tagged.size()); String sql = "DELETE FROM " + cacheTableName + " WHERE key IN ("; for (String key : tagged) { sql += "?,"; locks.add(lockSource.getWriteLock(key)); } sql = sql.substring(0, sql.length() - 1) + ")"; for (Lock lock : locks) lock.lock(); try { PreparedStatement statement = connection.prepareStatement(sql); try { int i = 1; for (String key : tagged) statement.setString(i++, key); if (!statement.execute()) logger.fine("Invalidated " + statement.getUpdateCount()); } finally { statement.close(); } for (String key : tagged) lockSource.discard(key); } finally { for (Lock lock : locks) lock.unlock(); } } finally { connection.close(); } } catch (SQLException x) { logger.log(Level.WARNING, "Could not invalidate cache tag", x); } }
From source file:com.mirth.connect.connectors.jdbc.DatabaseDispatcherQuery.java
@Override public Response send(DatabaseDispatcherProperties connectorProperties, ConnectorMessage connectorMessage) throws DatabaseDispatcherException { long dispatcherId = connector.getDispatcherId(); SimpleDataSource dataSource = dataSources.get(dispatcherId); if (dataSource == null) { dataSource = new SimpleDataSource(); dataSources.put(dispatcherId, dataSource); }/*from www . ja va2s .c o m*/ PreparedStatement statement = null; try { Connection connection = dataSource.getConnection(connectorProperties); statement = connection.prepareStatement(connectorProperties.getQuery()); int i = 1; for (Object param : connectorProperties.getParameters()) { statement.setObject(i++, param); } /* * We do not use Statement.executeUpdate() here because it could prevent users from * executing a stored procedure. Executing a stored procedure in Postgres (and possibly * other databases) is done via SELECT myprocedure(), which breaks executeUpdate() since * it returns a result, even if the procedure itself returns void. */ statement.execute(); int numRows = statement.getUpdateCount(); String responseData = null; String responseMessageStatus = null; if (numRows == -1) { responseMessageStatus = "Database write success"; } else { responseMessageStatus = "Database write success, " + numRows + " rows updated"; } return new Response(Status.SENT, responseData, responseMessageStatus); } catch (Exception e) { throw new DatabaseDispatcherException("Failed to write to database", e); } finally { DbUtils.closeQuietly(statement); } }
From source file:org.biokoframework.system.repository.sql.SqlRepository.java
private DE update(DE entity) { boolean updated = false; Connection connection = null; PreparedStatement updateStatement = null; try {/*from ww w .jav a 2s. c o m*/ connection = fDbConnector.getConnection(); updateStatement = SqlStatementsHelper.preparedUpdateStatement(fEntityClass, fTableName, connection); int i = 1; for (Entry<String, Field> anEntry : fFieldNames.entrySet()) { String aFieldName = anEntry.getKey(); fTranslator.insertIntoStatement(aFieldName, entity.get(aFieldName), anEntry.getValue(), updateStatement, i); i++; } updateStatement.setString(fFieldNames.size() + 1, entity.getId()); updateStatement.execute(); updated = updateStatement.getUpdateCount() > 0; updateStatement.close(); connection.close(); } catch (SQLException exception) { LOGGER.error("Error in retrieve", exception); closeDumbSql(connection, updateStatement, null); } if (updated) { return entity; } else { return null; } }
From source file:org.wso2.carbon.appfactory.core.dao.JDBCAppVersionDAO.java
/** * Updates the promote status of an application version * * @param applicationKey application key * @param version version number/*w ww.j a va 2s . c o m*/ * @param status status of promotion * @return true if it a success; false if it a failure * @throws org.wso2.carbon.appfactory.common.AppFactoryException */ public boolean updatePromoteStatusOfVersion(String applicationKey, String version, String status) throws AppFactoryException { Connection databaseConnection = null; PreparedStatement preparedStatement = null; try { databaseConnection = AppFactoryDBUtil.getConnection(); preparedStatement = databaseConnection.prepareStatement(SQLConstants.UPDATE_PROMOTE_STATUS_OF_VERSION); preparedStatement.setString(1, status); preparedStatement.setInt(2, JDBCApplicationDAO.getInstance().getAutoIncrementAppID(applicationKey, databaseConnection)); preparedStatement.setString(3, version); preparedStatement.execute(); int affectedRows = preparedStatement.getUpdateCount(); if (affectedRows > 0) { databaseConnection.commit(); return true; } String msg = "Error while updating promote status of version : " + version; log.error(msg); throw new AppFactoryException(msg); } catch (SQLException e) { try { if (databaseConnection != null) { databaseConnection.rollback(); } } catch (SQLException e1) { // Only logging this exception since this is not the main issue. The original issue is thrown. log.error("Error while rolling back update promote status of version : " + version, e1); } String msg = "Error while updating promote status of version : " + version; log.error(msg, e); throw new AppFactoryException(msg, e); } finally { JDBCApplicationCacheManager.getAppVersionCache() .remove(JDBCApplicationCacheManager.constructAppVersionCacheKey(applicationKey, version)); JDBCApplicationCacheManager.getAppVersionListCache().remove(applicationKey); AppFactoryDBUtil.closePreparedStatement(preparedStatement); AppFactoryDBUtil.closeConnection(databaseConnection); } }