Java Code Examples for java.sql.CallableStatement#getUpdateCount()

The following examples show how to use java.sql.CallableStatement#getUpdateCount() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DalDirectClient.java    From das with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> autoExtractReturnedResults(CallableStatement statement, int updateCount)
        throws SQLException {
    Map<String, Object> returnedResults = new LinkedHashMap<String, Object>();
    boolean moreResults;
    int index = 0;
    DalRowMapperExtractor<Map<String, Object>> extractor;
    do {
        extractor = new DalRowMapperExtractor<>(new DalColumnMapRowMapper());
        String key = (updateCount == -1 ? "ResultSet_" : "UpdateCount_") + index;
        Object value = updateCount == -1 ? extractor.extract(statement.getResultSet()) : updateCount;
        moreResults = statement.getMoreResults();
        updateCount = statement.getUpdateCount();
        index++;
        returnedResults.put(key, value);
    } while (moreResults || updateCount != -1);

    return returnedResults;
}
 
Example 2
Source File: DalDirectClient.java    From dal with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> autoExtractReturnedResults(CallableStatement statement, int updateCount)
        throws SQLException {
    Map<String, Object> returnedResults = new LinkedHashMap<String, Object>();
    boolean moreResults;
    int index = 0;
    DalRowMapperExtractor<Map<String, Object>> extractor;
    do {
        extractor = new DalRowMapperExtractor<>(new DalColumnMapRowMapper());
        String key = (updateCount == -1 ? "ResultSet_" : "UpdateCount_") + index;
        Object value = updateCount == -1 ? extractor.extract(statement.getResultSet()) : updateCount;
        moreResults = statement.getMoreResults();
        updateCount = statement.getUpdateCount();
        index++;
        returnedResults.put(key, value);
    } while (moreResults || updateCount != -1);

    return returnedResults;
}
 
Example 3
Source File: MySQLDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ResultSet getResultSet(CallableStatement ps) throws SQLException {
	boolean isResultSet = ps.execute();
	while ( !isResultSet && ps.getUpdateCount() != -1 ) {
		isResultSet = ps.getMoreResults();
	}
	return ps.getResultSet();
}
 
Example 4
Source File: SybaseDialect.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public ResultSet getResultSet(CallableStatement ps) throws SQLException {
		boolean isResultSet = ps.execute();
//		 This assumes you will want to ignore any update counts
		while ( !isResultSet && ps.getUpdateCount() != -1 ) {
			isResultSet = ps.getMoreResults();
		}
//		 You may still have other ResultSets or update counts left to process here
//		 but you can't do it now or the ResultSet you just got will be closed
		return ps.getResultSet();
	}
 
Example 5
Source File: cfStoredProcData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void retrieveAndStoreResultSets(cfSession Session, String datasourceName, CallableStatement call) throws cfmRunTimeException {
	// the Oracle 10g JDBC driver has a bug: call.getUpdateCount() always
	// returns a positive number, instead of -1 when there are no more
	// results; this bug puts the following code into an infinite loop;
	// just return because Oracle returns result sets as output parameters
	// anyway (there are never any result sets returned here)
	if (call.getClass().getName().equals("oracle.jdbc.driver.T4CCallableStatement"))
		return;

	try {
		int currentResultSet = 1;

		do { // there may be multiple result sets and/or update counts
			ResultSet rs = call.getResultSet();
			if (rs != null) {
				resultSetHolder rsh = getResultSetHolder(currentResultSet);
				if (rsh != null) {
					Session.setData(rsh.name, new cfQueryResultData(rs, "Stored Procedure", rsh.maxRows));
				}
				currentResultSet++; // moved this out of the above 'if' clause to fix bug #2376
				rs.close();
			}
		} while (call.getMoreResults() || (call.getUpdateCount() >= 0));

	} catch (SQLException e) {
		throw new cfmRunTimeException(catchDataFactory.databaseException(datasourceName, "sql.storedProcedureResult", null, "", e));
	}
}
 
Example 6
Source File: DalDirectClient.java    From dal with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> extractReturnedResults(CallableStatement statement,
                                                   List<StatementParameter> resultParameters, int updateCount, DalHints hints) throws SQLException {
    Map<String, Object> returnedResults = new LinkedHashMap<String, Object>();
    if (hints.is(DalHintEnum.skipResultsProcessing))
        return returnedResults;

    if (hints.is(DalHintEnum.retrieveAllSpResults))
        return autoExtractReturnedResults(statement, updateCount);

    if (resultParameters.size() == 0)
        return returnedResults;

    boolean moreResults;
    int index = 0;
    do {
        // If resultParameters is not the same as what exactly returned, there will be exception. You just
        // need to add enough result parameter to avoid this or you can set skipResultsProcessing
        StatementParameter resultParameter = resultParameters.get(index);
        String key = resultParameter.getName();
        Object value = updateCount == -1
                ? resultParameters.get(index).getResultSetExtractor().extract(statement.getResultSet())
                : updateCount;
        resultParameter.setValue(value);
        moreResults = statement.getMoreResults();
        updateCount = statement.getUpdateCount();
        index++;
        returnedResults.put(key, value);
    } while (moreResults || updateCount != -1);

    return returnedResults;
}
 
Example 7
Source File: DB2Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ResultSet getResultSet(CallableStatement ps) throws SQLException {
	boolean isResultSet = ps.execute();
	// This assumes you will want to ignore any update counts
	while ( !isResultSet && ps.getUpdateCount() != -1 ) {
		isResultSet = ps.getMoreResults();
	}

	return ps.getResultSet();
}
 
Example 8
Source File: CallableStatementHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public int update(Statement statement) throws SQLException {
  //这个方法和PreparedStatementHandler代码基本一样,就多了最后的handleOutputParameters
  //调用Statement.execute和Statement.getUpdateCount
  CallableStatement cs = (CallableStatement) statement;
  cs.execute();
  int rows = cs.getUpdateCount();
  Object parameterObject = boundSql.getParameterObject();
  KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
  keyGenerator.processAfter(executor, mappedStatement, cs, parameterObject);
  //然后交给ResultSetHandler.handleOutputParameters
  resultSetHandler.handleOutputParameters(cs);
  return rows;
}
 
Example 9
Source File: DataDirectOracle9Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ResultSet getResultSet(CallableStatement ps) throws SQLException {
	boolean isResultSet = ps.execute();
	// This assumes you will want to ignore any update counts
	while (!isResultSet && ps.getUpdateCount() != -1) { 
		isResultSet = ps.getMoreResults();
	}

	return ps.getResultSet();
}
 
Example 10
Source File: Teradata14Dialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ResultSet getResultSet(CallableStatement cs) throws SQLException {
	boolean isResultSet = cs.execute();
	while ( !isResultSet && cs.getUpdateCount() != -1 ) {
		isResultSet = cs.getMoreResults();
	}
	return cs.getResultSet();
}
 
Example 11
Source File: CallableStatementHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public int update(Statement statement) throws SQLException {
  //这个方法和PreparedStatementHandler代码基本一样,就多了最后的handleOutputParameters
  //调用Statement.execute和Statement.getUpdateCount
  CallableStatement cs = (CallableStatement) statement;
  cs.execute();
  int rows = cs.getUpdateCount();
  Object parameterObject = boundSql.getParameterObject();
  KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
  keyGenerator.processAfter(executor, mappedStatement, cs, parameterObject);
  //然后交给ResultSetHandler.handleOutputParameters
  resultSetHandler.handleOutputParameters(cs);
  return rows;
}
 
Example 12
Source File: DalDirectClient.java    From das with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> extractReturnedResults(CallableStatement statement,
        List<Parameter> resultParameters, int updateCount, Hints hints) throws SQLException {
    Map<String, Object> returnedResults = new LinkedHashMap<String, Object>();
    if (hints.is(HintEnum.skipResultsProcessing)) {
        return returnedResults;
    }

    if (hints.is(HintEnum.retrieveAllSpResults)) {
        return autoExtractReturnedResults(statement, updateCount);
    }

    if (resultParameters.size() == 0) {
        return returnedResults;
    }

    boolean moreResults;
    int index = 0;
    do {
        // If resultParameters is not the same as what exactly returned, there will be exception. You just
        // need to add enough result parameter to avoid this or you can set skipResultsProcessing
        Parameter resultParameter = resultParameters.get(index);
        String key = resultParameter.getName();
        Object value = updateCount == -1
                ? resultParameters.get(index).getResultSetExtractor().extract(statement.getResultSet())
                : updateCount;
        resultParameter.setValue(value);
        moreResults = statement.getMoreResults();
        updateCount = statement.getUpdateCount();
        index++;
        returnedResults.put(key, value);
    } while (moreResults || updateCount != -1);

    return returnedResults;
}
 
Example 13
Source File: SWCallableStatementTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Test
public void testCallableStatementConfig() throws SQLException {
    CallableStatement callableStatement = swConnection.prepareCall("INSERT INTO test VALUES( ? , ?)", 1, 1);
    callableStatement.setInt(1, 1);
    callableStatement.setString(2, "a");
    callableStatement.getUpdateCount();
    callableStatement.setFetchDirection(1);
    callableStatement.getFetchDirection();
    callableStatement.getResultSetConcurrency();
    callableStatement.getResultSetType();
    callableStatement.isClosed();
    callableStatement.setPoolable(false);
    callableStatement.isPoolable();
    callableStatement.getWarnings();
    callableStatement.clearWarnings();
    callableStatement.setCursorName("test");
    callableStatement.setMaxFieldSize(11);
    callableStatement.getMaxFieldSize();
    callableStatement.setMaxRows(10);
    callableStatement.getMaxRows();
    callableStatement.getParameterMetaData();
    callableStatement.setEscapeProcessing(true);
    callableStatement.setFetchSize(1);
    callableStatement.getFetchSize();
    callableStatement.setQueryTimeout(1);
    callableStatement.getQueryTimeout();
    Connection connection = callableStatement.getConnection();

    callableStatement.execute();

    callableStatement.getMoreResults();
    callableStatement.getMoreResults(1);
    callableStatement.getResultSetHoldability();
    callableStatement.getMetaData();
    callableStatement.getResultSet();

    callableStatement.close();
    verify(mysqlCallableStatement).getUpdateCount();
    verify(mysqlCallableStatement).getMoreResults();
    verify(mysqlCallableStatement).setFetchDirection(anyInt());
    verify(mysqlCallableStatement).getFetchDirection();
    verify(mysqlCallableStatement).getResultSetType();
    verify(mysqlCallableStatement).isClosed();
    verify(mysqlCallableStatement).setPoolable(anyBoolean());
    verify(mysqlCallableStatement).getWarnings();
    verify(mysqlCallableStatement).clearWarnings();
    verify(mysqlCallableStatement).setCursorName(anyString());
    verify(mysqlCallableStatement).setMaxFieldSize(anyInt());
    verify(mysqlCallableStatement).getMaxFieldSize();
    verify(mysqlCallableStatement).setMaxRows(anyInt());
    verify(mysqlCallableStatement).getMaxRows();
    verify(mysqlCallableStatement).setEscapeProcessing(anyBoolean());
    verify(mysqlCallableStatement).getResultSetConcurrency();
    verify(mysqlCallableStatement).getResultSetConcurrency();
    verify(mysqlCallableStatement).getResultSetType();
    verify(mysqlCallableStatement).getMetaData();
    verify(mysqlCallableStatement).getParameterMetaData();
    verify(mysqlCallableStatement).getMoreResults(anyInt());
    verify(mysqlCallableStatement).setFetchSize(anyInt());
    verify(mysqlCallableStatement).getFetchSize();
    verify(mysqlCallableStatement).getQueryTimeout();
    verify(mysqlCallableStatement).setQueryTimeout(anyInt());
    verify(mysqlCallableStatement).getResultSet();
    assertThat(connection, CoreMatchers.<Connection>is(swConnection));
}
 
Example 14
Source File: JdbcTemplate.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Extract returned ResultSets from the completed stored procedure.
 * @param cs JDBC wrapper for the stored procedure
 * @param updateCountParameters Parameter list of declared update count parameters for the stored procedure
 * @param resultSetParameters Parameter list of declared resultSet parameters for the stored procedure
 * @return Map that contains returned results
 */
protected Map<String, Object> extractReturnedResults(CallableStatement cs,
		List<SqlParameter> updateCountParameters, List<SqlParameter> resultSetParameters, int updateCount)
		throws SQLException {

	Map<String, Object> returnedResults = new HashMap<String, Object>();
	int rsIndex = 0;
	int updateIndex = 0;
	boolean moreResults;
	if (!this.skipResultsProcessing) {
		do {
			if (updateCount == -1) {
				if (resultSetParameters != null && resultSetParameters.size() > rsIndex) {
					SqlReturnResultSet declaredRsParam = (SqlReturnResultSet) resultSetParameters.get(rsIndex);
					returnedResults.putAll(processResultSet(cs.getResultSet(), declaredRsParam));
					rsIndex++;
				}
				else {
					if (!this.skipUndeclaredResults) {
						String rsName = RETURN_RESULT_SET_PREFIX + (rsIndex + 1);
						SqlReturnResultSet undeclaredRsParam = new SqlReturnResultSet(rsName, getColumnMapRowMapper());
						if (logger.isDebugEnabled()) {
							logger.debug("Added default SqlReturnResultSet parameter named '" + rsName + "'");
						}
						returnedResults.putAll(processResultSet(cs.getResultSet(), undeclaredRsParam));
						rsIndex++;
					}
				}
			}
			else {
				if (updateCountParameters != null && updateCountParameters.size() > updateIndex) {
					SqlReturnUpdateCount ucParam = (SqlReturnUpdateCount) updateCountParameters.get(updateIndex);
					String declaredUcName = ucParam.getName();
					returnedResults.put(declaredUcName, updateCount);
					updateIndex++;
				}
				else {
					if (!this.skipUndeclaredResults) {
						String undeclaredName = RETURN_UPDATE_COUNT_PREFIX + (updateIndex + 1);
						if (logger.isDebugEnabled()) {
							logger.debug("Added default SqlReturnUpdateCount parameter named '" + undeclaredName + "'");
						}
						returnedResults.put(undeclaredName, updateCount);
						updateIndex++;
					}
				}
			}
			moreResults = cs.getMoreResults();
			updateCount = cs.getUpdateCount();
			if (logger.isDebugEnabled()) {
				logger.debug("CallableStatement.getUpdateCount() returned " + updateCount);
			}
		}
		while (moreResults || updateCount != -1);
	}
	return returnedResults;
}
 
Example 15
Source File: SQLServerDbWriteAccess.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
public boolean insertSuiteMessage(
                                   String message,
                                   int level,
                                   boolean escapeHtml,
                                   String machineName,
                                   String threadName,
                                   long timestamp,
                                   int suiteId,
                                   boolean closeConnection ) throws DatabaseAccessException {

    String dbVersionString = getDatabaseVersion();
    int dbVersion = Integer.parseInt(dbVersionString.replace(".", ""));

    if (dbVersion < 350) {

        return false;
    } else {

        timestamp = inUTC(timestamp);

        Connection currentConnection;
        if (!isBatchMode) {
            currentConnection = refreshInternalConnection();
        } else {
            currentConnection = dbEventsCache.connection;
        }

        CallableStatement insertMessageStatement = insertFactory.getInsertSuiteMessageStatement(currentConnection,
                                                                                                message,
                                                                                                level,
                                                                                                escapeHtml,
                                                                                                machineName,
                                                                                                threadName,
                                                                                                timestamp,
                                                                                                suiteId);

        if (isBatchMode) {
            // schedule this event for batch execution
            return dbEventsCache.addInsertSuiteMessageEventToBatch(insertMessageStatement);
        } else {
            // execute this event now
            String errMsg = "Unable to insert suite message '" + message + "'";

            try {
                insertMessageStatement.execute();
                if (insertMessageStatement.getUpdateCount() < 1) {
                    throw new DatabaseAccessException(errMsg);
                }
            } catch (SQLException e) {
                String procedureName = "sp_insert_suite_message";
                List<Object> argValues = new ArrayList<Object>();
                argValues.add(suiteId);
                argValues.add(level);
                argValues.add(message);
                argValues.add(escapeHtml);
                argValues.add(machineName);
                argValues.add(threadName);
                argValues.add(timestamp);

                errMsg += " using the following statement: "
                          + constructStoredProcedureArgumentsMap(procedureName, argValues);
                throw new DatabaseAccessException(errMsg, e);
            } finally {
                if (closeConnection) {
                    DbUtils.close(connection, insertMessageStatement);
                } else {
                    DbUtils.closeStatement(insertMessageStatement);
                }
            }

            return false;
        }
    }
}
 
Example 16
Source File: SQLServerDbWriteAccess.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
public boolean insertRunMessage(
                                 String message,
                                 int level,
                                 boolean escapeHtml,
                                 String machineName,
                                 String threadName,
                                 long timestamp,
                                 int runId,
                                 boolean closeConnection ) throws DatabaseAccessException {

    String dbVersionString = getDatabaseVersion();
    int dbVersion = Integer.parseInt(dbVersionString.replace(".", "")); // TODO: fix version conversion like in 2 digit number cases

    if (dbVersion < 350) {

        return false;
    } else {

        timestamp = inUTC(timestamp);

        Connection currentConnection;
        if (!isBatchMode) {
            currentConnection = refreshInternalConnection();
        } else {
            currentConnection = dbEventsCache.connection;
        }

        CallableStatement insertMessageStatement = insertFactory.getInsertRunMessageStatement(currentConnection,
                                                                                              message,
                                                                                              level,
                                                                                              escapeHtml,
                                                                                              machineName,
                                                                                              threadName,
                                                                                              timestamp,
                                                                                              runId);

        if (isBatchMode) {
            // schedule this event for batch execution
            return dbEventsCache.addInsertRunMessageEventToBatch(insertMessageStatement);
        } else {
            // execute this event now
            String errMsg = "Unable to insert run message '" + message + "'";

            try {
                insertMessageStatement.execute();
                if (insertMessageStatement.getUpdateCount() < 1) {
                    throw new DatabaseAccessException(errMsg);
                }
            } catch (SQLException e) {
                String procedureName = "sp_insert_run_message";
                List<Object> argValues = new ArrayList<Object>();
                argValues.add(runId);
                argValues.add(level);
                argValues.add(message);
                argValues.add(escapeHtml);
                argValues.add(machineName);
                argValues.add(threadName);
                argValues.add(timestamp);

                errMsg += " using the following statement: "
                          + constructStoredProcedureArgumentsMap(procedureName, argValues);
                throw new DatabaseAccessException(errMsg, e);
            } finally {
                if (closeConnection) {
                    DbUtils.close(connection, insertMessageStatement);
                } else {
                    DbUtils.closeStatement(insertMessageStatement);
                }
            }

            return false;
        }
    }
}
 
Example 17
Source File: TestPreparedStatements.java    From evosql with Apache License 2.0 4 votes vote down vote up
public void testB() throws SQLException, ClassNotFoundException {

        Statement statement = con.createStatement();

        statement.execute(
            "CREATE TABLE IF NOT EXISTS users (id INTEGER, name VARCHAR(25), PRIMARY KEY(id))");
        statement.executeUpdate("INSERT INTO users VALUES(1, 'Ramiro')");
        statement.executeUpdate("INSERT INTO users VALUES(2, 'Chanukya')");

        String storedProcedure1 =
            "CREATE PROCEDURE sp_say_hi(IN greeting_p VARCHAR(10)) "
            + "READS SQL DATA DYNAMIC RESULT SETS 2 " + "BEGIN ATOMIC "
            + "DECLARE result CURSOR WITH RETURN FOR SELECT COALESCE(greeting_p, 'Hi')+' '+name as greeting FROM users FOR READ ONLY; "
            + "DECLARE result1 CURSOR WITH RETURN FOR SELECT * FROM users FOR READ ONLY; "
            + "OPEN result; " + "OPEN result1; " + "END";

        statement.execute(storedProcedure1);

        String            sqlCall           = "CALL sp_say_hi(?)";
        CallableStatement callableStatement = con.prepareCall(sqlCall);

        callableStatement.setObject("GREETING_P", "Hola");

        boolean result = callableStatement.execute();

        if (!result) {
            int value = callableStatement.getUpdateCount();

            assertTrue(value == 0);
            result = callableStatement.getMoreResults();
            assertTrue(result);
            ResultSet result1 = callableStatement.getResultSet();
            result = callableStatement.getMoreResults();
            assertTrue(result);
            ResultSet result2 = callableStatement.getResultSet();
            result = callableStatement.getMoreResults();
            assertFalse(result);
            value = callableStatement.getUpdateCount();
            assertTrue(value == -1);

        }
    }
 
Example 18
Source File: JdbcTemplate.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Extract returned ResultSets from the completed stored procedure.
 * @param cs JDBC wrapper for the stored procedure
 * @param updateCountParameters Parameter list of declared update count parameters for the stored procedure
 * @param resultSetParameters Parameter list of declared resultSet parameters for the stored procedure
 * @return Map that contains returned results
 */
protected Map<String, Object> extractReturnedResults(CallableStatement cs,
		List<SqlParameter> updateCountParameters, List<SqlParameter> resultSetParameters, int updateCount)
		throws SQLException {

	Map<String, Object> returnedResults = new HashMap<String, Object>();
	int rsIndex = 0;
	int updateIndex = 0;
	boolean moreResults;
	if (!this.skipResultsProcessing) {
		do {
			if (updateCount == -1) {
				if (resultSetParameters != null && resultSetParameters.size() > rsIndex) {
					SqlReturnResultSet declaredRsParam = (SqlReturnResultSet) resultSetParameters.get(rsIndex);
					returnedResults.putAll(processResultSet(cs.getResultSet(), declaredRsParam));
					rsIndex++;
				}
				else {
					if (!this.skipUndeclaredResults) {
						String rsName = RETURN_RESULT_SET_PREFIX + (rsIndex + 1);
						SqlReturnResultSet undeclaredRsParam = new SqlReturnResultSet(rsName, new ColumnMapRowMapper());
						if (logger.isDebugEnabled()) {
							logger.debug("Added default SqlReturnResultSet parameter named '" + rsName + "'");
						}
						returnedResults.putAll(processResultSet(cs.getResultSet(), undeclaredRsParam));
						rsIndex++;
					}
				}
			}
			else {
				if (updateCountParameters != null && updateCountParameters.size() > updateIndex) {
					SqlReturnUpdateCount ucParam = (SqlReturnUpdateCount) updateCountParameters.get(updateIndex);
					String declaredUcName = ucParam.getName();
					returnedResults.put(declaredUcName, updateCount);
					updateIndex++;
				}
				else {
					if (!this.skipUndeclaredResults) {
						String undeclaredName = RETURN_UPDATE_COUNT_PREFIX + (updateIndex + 1);
						if (logger.isDebugEnabled()) {
							logger.debug("Added default SqlReturnUpdateCount parameter named '" + undeclaredName + "'");
						}
						returnedResults.put(undeclaredName, updateCount);
						updateIndex++;
					}
				}
			}
			moreResults = cs.getMoreResults();
			updateCount = cs.getUpdateCount();
			if (logger.isDebugEnabled()) {
				logger.debug("CallableStatement.getUpdateCount() returned " + updateCount);
			}
		}
		while (moreResults || updateCount != -1);
	}
	return returnedResults;
}
 
Example 19
Source File: SQLServerDbWriteAccess.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
public boolean insertMessage(
                              String message,
                              int level,
                              boolean escapeHtml,
                              String machineName,
                              String threadName,
                              long timestamp,
                              int testCaseId,
                              boolean closeConnection ) throws DatabaseAccessException {

    timestamp = inUTC(timestamp);

    Connection currentConnection;
    if (!isBatchMode) {
        currentConnection = refreshInternalConnection();
    } else {
        currentConnection = dbEventsCache.connection;
    }

    CallableStatement insertMessageStatement = insertFactory.getInsertTestcaseMessageStatement(currentConnection,
                                                                                               message,
                                                                                               level,
                                                                                               escapeHtml,
                                                                                               machineName,
                                                                                               threadName,
                                                                                               timestamp,
                                                                                               testCaseId);

    if (isBatchMode) {
        // schedule this event for batch execution
        return dbEventsCache.addInsertTestcaseMessageEventToBatch(insertMessageStatement);
    } else {
        // execute this event now
        String errMsg = "Unable to insert testcase message '" + message + "'";

        try {
            insertMessageStatement.execute();

            if (insertMessageStatement.getUpdateCount() < 1) {
                throw new DatabaseAccessException(errMsg);
            }
        } catch (SQLException e) {
            String procedureName = "sp_insert_message";
            List<Object> argValues = new ArrayList<Object>();
            argValues.add(testCaseId);
            argValues.add(level);
            argValues.add(message);
            argValues.add(escapeHtml);
            argValues.add(machineName);
            argValues.add(threadName);
            argValues.add(timestamp);

            errMsg += " using the following statement: "
                      + constructStoredProcedureArgumentsMap(procedureName, argValues);
            throw new DatabaseAccessException(errMsg, e);
        } finally {
            if (closeConnection) {
                DbUtils.close(connection, insertMessageStatement);
            } else {
                DbUtils.closeStatement(insertMessageStatement);
            }
        }

        return false;
    }
}
 
Example 20
Source File: JdbcTemplate.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Extract returned ResultSets from the completed stored procedure.
 * @param cs a JDBC wrapper for the stored procedure
 * @param updateCountParameters the parameter list of declared update count parameters for the stored procedure
 * @param resultSetParameters the parameter list of declared resultSet parameters for the stored procedure
 * @return a Map that contains returned results
 */
protected Map<String, Object> extractReturnedResults(CallableStatement cs,
		@Nullable List<SqlParameter> updateCountParameters, @Nullable List<SqlParameter> resultSetParameters,
		int updateCount) throws SQLException {

	Map<String, Object> results = new LinkedHashMap<>(4);
	int rsIndex = 0;
	int updateIndex = 0;
	boolean moreResults;
	if (!this.skipResultsProcessing) {
		do {
			if (updateCount == -1) {
				if (resultSetParameters != null && resultSetParameters.size() > rsIndex) {
					SqlReturnResultSet declaredRsParam = (SqlReturnResultSet) resultSetParameters.get(rsIndex);
					results.putAll(processResultSet(cs.getResultSet(), declaredRsParam));
					rsIndex++;
				}
				else {
					if (!this.skipUndeclaredResults) {
						String rsName = RETURN_RESULT_SET_PREFIX + (rsIndex + 1);
						SqlReturnResultSet undeclaredRsParam = new SqlReturnResultSet(rsName, getColumnMapRowMapper());
						if (logger.isTraceEnabled()) {
							logger.trace("Added default SqlReturnResultSet parameter named '" + rsName + "'");
						}
						results.putAll(processResultSet(cs.getResultSet(), undeclaredRsParam));
						rsIndex++;
					}
				}
			}
			else {
				if (updateCountParameters != null && updateCountParameters.size() > updateIndex) {
					SqlReturnUpdateCount ucParam = (SqlReturnUpdateCount) updateCountParameters.get(updateIndex);
					String declaredUcName = ucParam.getName();
					results.put(declaredUcName, updateCount);
					updateIndex++;
				}
				else {
					if (!this.skipUndeclaredResults) {
						String undeclaredName = RETURN_UPDATE_COUNT_PREFIX + (updateIndex + 1);
						if (logger.isTraceEnabled()) {
							logger.trace("Added default SqlReturnUpdateCount parameter named '" + undeclaredName + "'");
						}
						results.put(undeclaredName, updateCount);
						updateIndex++;
					}
				}
			}
			moreResults = cs.getMoreResults();
			updateCount = cs.getUpdateCount();
			if (logger.isTraceEnabled()) {
				logger.trace("CallableStatement.getUpdateCount() returned " + updateCount);
			}
		}
		while (moreResults || updateCount != -1);
	}
	return results;
}