List of usage examples for java.sql CallableStatement getMoreResults
boolean getMoreResults() throws SQLException;
Statement
object's next result, returns true
if it is a ResultSet
object, and implicitly closes any current ResultSet
object(s) obtained with the method getResultSet
. From source file:Main.java
public static void main(String args[]) throws Exception { String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs"; String userName = "yourUser"; String password = "yourPassword"; Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); Connection con = DriverManager.getConnection(URL, userName, password); CallableStatement callstmt = con .prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT @@IDENTITY"); callstmt.setString(1, "testInputBatch"); callstmt.execute();//ww w .j av a 2s . c o m int iUpdCount = callstmt.getUpdateCount(); boolean bMoreResults = true; ResultSet rs = null; int myIdentVal = -1; // to store the @@IDENTITY while (bMoreResults || iUpdCount != -1) { rs = callstmt.getResultSet(); if (rs != null) { rs.next(); myIdentVal = rs.getInt(1); } bMoreResults = callstmt.getMoreResults(); iUpdCount = callstmt.getUpdateCount(); } callstmt.close(); con.close(); }
From source file:org.marccarre.spring.db.testing.FooDao.java
public List<Foo> getByIdCallableStatement(int id) { final int fooId = id; return jdbcTemplate.execute(new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection con) throws SQLException { CallableStatement cs = con.prepareCall("{call GetFoosById(?)}"); cs.setInt(1, fooId);/*from w ww . j a v a 2 s. c om*/ return cs; } }, new CallableStatementCallback<List<Foo>>() { public List<Foo> doInCallableStatement(CallableStatement cs) throws SQLException { cs.execute(); List<Foo> foos = new ArrayList<Foo>(); if (cs.getMoreResults()) { ResultSet rs = cs.getResultSet(); FooRowMapper mapper = new FooRowMapper(); int rowIndex = 0; while (rs.next()) { foos.add(mapper.mapRow(rs, rowIndex)); rowIndex++; } } return foos; } }); }
From source file:com.hangum.tadpole.sql.util.executer.procedure.MSSQLProcedureExecuter.java
@Override public boolean exec(List<InOutParameterDAO> parameterList) throws Exception { initResult();//from w w w .j av a2 s . c om java.sql.Connection javaConn = null; java.sql.CallableStatement cstmt = null; try { if (listOutParamValues == null) getOutParameters(); SqlMapClient client = TadpoleSQLManager.getInstance(userDB); javaConn = client.getDataSource().getConnection(); // make the script String[] arrProcedureName = StringUtils.split(procedureDAO.getName(), "."); String strProcName = "[" + arrProcedureName[0] + "].[" + arrProcedureName[1] + "]"; StringBuffer sbQuery = new StringBuffer("{call " + strProcName + "("); // in script int intParamSize = this.getParametersCount(); for (int i = 0; i < intParamSize; i++) { if (i == 0) sbQuery.append("?"); else sbQuery.append(",?"); } sbQuery.append(")}"); if (logger.isDebugEnabled()) logger.debug("Execute Procedure query is\t " + sbQuery.toString()); // set prepare call cstmt = javaConn.prepareCall(sbQuery.toString()); // Set input value for (InOutParameterDAO inOutParameterDAO : parameterList) { // if(logger.isDebugEnabled()) logger.debug("Parameter " + inOutParameterDAO.getOrder() + " Value is " + inOutParameterDAO.getValue()); // if (null==inOutParameterDAO.getValue() || "".equals(inOutParameterDAO.getValue())){ // MessageDialog.openError(null, "Error", inOutParameterDAO.getName() + " parameters are required."); // return false; // } cstmt.setObject(inOutParameterDAO.getOrder(), inOutParameterDAO.getValue()); } // Set the OUT Parameter for (int i = 0; i < listOutParamValues.size(); i++) { InOutParameterDAO dao = listOutParamValues.get(i); if (logger.isDebugEnabled()) logger.debug("Out Parameter " + dao.getOrder() + " JavaType is " + RDBTypeToJavaTypeUtils.getJavaType(dao.getRdbType())); cstmt.registerOutParameter(dao.getOrder(), RDBTypeToJavaTypeUtils.getJavaType(dao.getRdbType())); } cstmt.execute(); // // set // // cursor list // boolean is cursor boolean isCursor = false; ResultSet rs = cstmt.getResultSet(); if (rs != null) { setResultCursor(rs); isCursor = true; // mssql? result set? ? ?. while (cstmt.getMoreResults()) { setResultCursor(cstmt.getResultSet()); } } else { for (int i = 0; i < listOutParamValues.size(); i++) { InOutParameterDAO dao = listOutParamValues.get(i); Object obj = cstmt.getObject(dao.getOrder()); // String? Type Cast .... String ... if (obj != null) { dao.setValue(obj.toString()); } } } if (!isCursor) { List<Map<Integer, Object>> sourceDataList = new ArrayList<Map<Integer, Object>>(); Map<Integer, Object> tmpRow = null; for (int i = 0; i < listOutParamValues.size(); i++) { InOutParameterDAO dao = listOutParamValues.get(i); tmpRow = new HashMap<Integer, Object>(); tmpRow.put(0, "" + dao.getOrder()); tmpRow.put(1, "" + dao.getName()); tmpRow.put(2, "" + dao.getType()); tmpRow.put(3, "" + dao.getRdbType()); tmpRow.put(4, "" + dao.getLength()); tmpRow.put(5, "" + dao.getValue()); sourceDataList.add(tmpRow); } setResultNoCursor(new TadpoleResultSet(sourceDataList)); } return true; } catch (Exception e) { logger.error("ProcedureExecutor executing error", e); throw e; } finally { try { if (cstmt != null) cstmt.close(); } catch (Exception e) { } try { if (javaConn != null) javaConn.close(); } catch (Exception e) { } } }
From source file:lib.JdbcTemplate.java
/** * 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 */// w w w . j a va 2s. c om 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; }
From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java
/** * Similar to the same method in original pubtest utility, but doesn't throw an exception if 0 rows are returned * and uses existing(established) JDBC connection corresponding to its published datasource name. * /* w ww . j av a 2 s .c o m*/ */ public static String executeProcedure(RegressionItem item, HashMap<String, Connection> cisConnections, String outputFile, String delimiter, String printOutputType) throws CompositeException { // Set the command and action name String command = "executeProcedure"; String actionName = "REGRESSION_TEST"; int rows = 0; String result = null; Connection conn = null; CallableStatement stmt = null; ResultSet rs = null; start = System.currentTimeMillis(); long firstRowLatency = 0L; // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { try { conn = getJdbcConnection(item.database, cisConnections); // don't need to check for null here. String URL = null; String userName = null; if (conn.getMetaData() != null) { if (conn.getMetaData().getURL() != null) URL = conn.getMetaData().getURL(); if (conn.getMetaData().getUserName() != null) userName = conn.getMetaData().getUserName(); } RegressionManagerUtils.printOutputStr(printOutputType, "debug", "RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delimiter, printOutputType). item.database=" + item.database + " cisConnections.URL=" + URL + " cisConnections.userName=" + userName + " outputFile=" + outputFile + " delimiter=" + delimiter + " printOutputType=" + printOutputType, ""); RegressionManagerUtils.printOutputStr(printOutputType, "debug", "DEBUG: connection to DB successful", ""); String query = item.input.replaceAll("\n", " "); // Convert a CALL statement into a SELECT * FROM statement // { CALL SCH1.LookupProduct( 3 ) } --> SCH1.LookupProduce( 3 ) if (query.toUpperCase().contains("CALL")) { query = "SELECT * FROM " + RegressionManagerUtils.getProcedure(query); ; } // Prepare the query stmt = (CallableStatement) conn.prepareCall(query); // Register output parameter types for (int i = 0; i < item.outTypes.length; i++) { if (!"-".equals(item.outTypes[i])) { int jdbcType = -1; try { jdbcType = Types.class.getField(item.outTypes[i]).getInt(null); } catch (Exception e) { RegressionManagerUtils.error(item.lineNum, item.outTypes[i], "No such JDBC type in java.sql.Types"); } stmt.registerOutParameter(i + 1, jdbcType); } } stmt.executeQuery(); // Print scalars ParameterMetaData pmd = stmt.getParameterMetaData(); int params = pmd.getParameterCount(); boolean addSep = false; String content = ""; for (int i = 0; i < params; i++) { if (addSep) { content += delimiter; } if (stmt.getObject(i + 1) != null) content += stmt.getObject(i + 1).toString(); else content += ""; addSep = true; } if (outputFile != null) CommonUtils.appendContentToFile(outputFile, content); RegressionManagerUtils.printOutputStr(printOutputType, "results", content, ""); // Get the result cursor and metadata cursor rs = stmt.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); int columns = rsmd.getColumnCount(); // Get the column metadata addSep = false; content = ""; for (int i = 0; i < columns; i++) { if (addSep) { content += delimiter; } if (rsmd.getColumnName(i + 1) != null) content += rsmd.getColumnName(i + 1).toString(); else content += ""; addSep = true; } if (outputFile != null) CommonUtils.appendContentToFile(outputFile, content); RegressionManagerUtils.printOutputStr(printOutputType, "results", content, ""); // Print cursors boolean firstRow = true; while (rs != null) { // Read the values while (rs.next()) { if (firstRow) { firstRowLatency = System.currentTimeMillis() - start; firstRow = false; } addSep = false; content = ""; for (int i = 0; i < columns; i++) { if (addSep) { content += delimiter; } if (rs.getObject(i + 1) != null) content += rs.getObject(i + 1).toString(); else content += ""; addSep = true; } if (outputFile != null) CommonUtils.appendContentToFile(outputFile, content); RegressionManagerUtils.printOutputStr(printOutputType, "results", content, ""); rows++; } stmt.getMoreResults(); rs = stmt.getResultSet(); } } catch (SQLException e) { throw new CompositeException("executeProcedure(): " + e.getMessage()); } catch (Exception e) { throw new CompositeException("executeProcedure(): " + e.getMessage()); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { rs = null; stmt = null; throw new CompositeException( "executeProcedure(): unable to close ResultSet or Statement" + e.getMessage()); } } RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeProcedure()", ""); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } // <rows>:<firstRowLatency> result = "" + rows + ":" + firstRowLatency; return result; /* Note: to process this result string on the client invocation side use the following pattern: * * String result = RegressionManagerUtils.executeQuery(item, cisConnections, outputFile, delim, printOutputType, "results"); String results[] = result.split(":"); if (results.length > 1) { rowCount = Integer.valueOf(results[0]); firstRowLatency.addAndGet(Long.parseLong(results[1])); } */ }
From source file:org.castor.cpa.persistence.sql.keygen.SequenceDuringKeyGenerator.java
/** * {@inheritDoc}/*w w w . j av a 2s.co m*/ */ public Object executeStatement(final Database database, final CastorConnection conn, final Identity identity, final ProposedEntity entity) throws PersistenceException { CastorStatement stmt = conn.createStatement(); CallableStatement cstmt = null; try { SQLColumnInfo[] ids = _engine.getColumnInfoForIdentities(); stmt.prepareStatement(_insert); String statement = stmt.toString(); statement += " RETURNING "; statement += _factory.quoteName(ids[0].getName()); statement += " INTO ?"; statement = "{call " + statement + "}"; stmt.setStatement(conn.getConnection().prepareCall(statement)); if (LOG.isTraceEnabled()) { LOG.trace(Messages.format("jdo.creating", _engineType, stmt.toString())); } bindFields(entity, stmt); if (LOG.isTraceEnabled()) { LOG.trace(Messages.format("jdo.creating", _engineType, stmt.toString())); } // generate key during INSERT. cstmt = (CallableStatement) stmt.getStatement(); int sqlType = ids[0].getSqlType(); cstmt.registerOutParameter(stmt.getParameterSize() + 1, sqlType); if (LOG.isDebugEnabled()) { LOG.debug(Messages.format("jdo.creating", _engineType, cstmt.toString())); } cstmt.execute(); // first skip all results "for maximum portability" // as proposed in CallableStatement javadocs. while (cstmt.getMoreResults() || (cstmt.getUpdateCount() != -1)) { // no code to execute } // identity is returned in the last parameter. // workaround for INTEGER type in Oracle getObject returns BigDecimal. Object temp; if (sqlType == java.sql.Types.INTEGER) { temp = new Integer(cstmt.getInt(stmt.getParameterSize() + 1)); } else { temp = cstmt.getObject(stmt.getParameterSize() + 1); } return new Identity(ids[0].toJava(temp)); } catch (SQLException except) { LOG.fatal(Messages.format("jdo.storeFatal", _engineType, stmt.toString()), except); throw new PersistenceException(Messages.format("persist.nested", except), except); } finally { //close statement try { if (cstmt != null) { cstmt.close(); } } catch (SQLException e) { LOG.warn("Problem closing JDBC statement", e); } try { stmt.close(); } catch (SQLException e) { LOG.warn("Problem closing JDBC statement", e); } } }
From source file:org.rimudb.storedproc.StoredProcedure.java
public List execute(boolean autoCommit) throws RimuDBException { ArrayList resultList = null;/*from www . java 2 s. com*/ Connection conn = null; int statID = 0; CallableStatement stmt = null; boolean originalAutoCommit = false; try { // Get a connection conn = database.getDatabaseConnection(); originalAutoCommit = conn.getAutoCommit(); conn.setAutoCommit(autoCommit); String sql = createSQL(); // Get the statistic ID int loggingType = database.getDatabaseConfiguration().getLoggingType(); if (loggingType == DatabaseConfiguration.LOG_STATISTICS) { statID = StatisticCollector.getInstance().createStatistic(sql); } else if (loggingType == DatabaseConfiguration.LOG_SQL_ONLY) { log.info("SQL=" + sql); } // Prepare the call stmt = conn.prepareCall(sql); int parameterCount = 0; if (getReturnType() != NONE) { parameterCount++; stmt.registerOutParameter(parameterCount, getReturnType()); } // Assign parameters for (int i = 0; i < parameterList.size(); i++) { parameterCount++; // If the parameter is an IN type parameter then if (parameterList.get(i) instanceof StoredProcINParameter || parameterList.get(i) instanceof StoredProcINOUTParameter) { stmt.setObject(parameterCount, parameterList.get(i).getValue()); } // If the parameter is an OUT type if (parameterList.get(i) instanceof StoredProcOUTParameter) { stmt.registerOutParameter(parameterCount, ((StoredProcOUTParameter) parameterList.get(i)).getSqlType()); } // If the parameter is an INOUT type if (parameterList.get(i) instanceof StoredProcINOUTParameter) { stmt.registerOutParameter(parameterCount, ((StoredProcINOUTParameter) parameterList.get(i)).getSqlType()); } } if (statID > 0) StatisticCollector.getInstance().logEvent(statID, "preparetime"); // Execute the call boolean result = stmt.execute(); if (statID > 0) StatisticCollector.getInstance().logEvent(statID, "executetime"); // If we got a result set if (result) { // Create the empty list to contain the rows resultList = new ArrayList(); // While there is a result set to be retrieved while (result) { // Get the result set ResultSet rs = stmt.getResultSet(); // Process the result set List list = processResultSet(rs); // And close the result set rs.close(); // Add the result set to the full list if (list != null) { resultList.addAll(list); } // Check for more results result = stmt.getMoreResults(); } } // If there was a return value if (getReturnType() != NONE) { Object value = stmt.getObject(1); if (value instanceof ResultSet) { resultList = new ArrayList(); ResultSet rs = (ResultSet) value; List list = processResultSet(rs); rs.close(); if (list != null) { resultList.addAll(list); } } else { returnValue = value; } } // Assign the out values for (int i = 0; i < parameterList.size(); i++) { // If the parameter is an OUT type if (parameterList.get(i) instanceof StoredProcOUTParameter || parameterList.get(i) instanceof StoredProcINOUTParameter) { Object value = stmt.getObject(i + 1); // Don't save ResultSets in the parameters if (!(value instanceof ResultSet)) { parameterList.get(i).setValue(value); } } } if (statID > 0) { StatisticCollector.getInstance().logEvent(statID, "processtime"); if (StatisticCollector.getInstance().exceedsThreshold(statID, database.getDatabaseConfiguration().getLoggingThreshold())) { String text = StatisticCollector.getInstance().formatStatistics(statID, database.getStatisticFormatter()); log.info(text); } StatisticCollector.getInstance().removeID(statID); } return resultList; } catch (SQLException e) { throw new RimuDBException(e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { // Don't care about a failure here } } if (conn != null) { try { conn.setAutoCommit(originalAutoCommit); conn.close(); } catch (SQLException e) { // Don't care about a failure here } } } }
From source file:org.seasar.dbflute.logic.sql2entity.cmentity.DfProcedureExecutionMetaExtractor.java
protected void doExtractExecutionMetaData(DataSource dataSource, DfProcedureMeta procedure) throws SQLException { final List<DfProcedureColumnMeta> columnList = procedure.getProcedureColumnList(); if (!needsToCall(columnList)) { final String name = procedure.buildProcedureLoggingName(); _log.info("*not needed to call: " + name + " params=" + buildParameterTypeView(columnList)); return;/*from w w w . j ava2 s . c o m*/ } final List<Object> testValueList = DfCollectionUtil.newArrayList(); setupTestValueList(columnList, testValueList); final boolean existsReturn = existsReturnValue(columnList); final String sql = createSql(procedure, existsReturn, true); Connection conn = null; CallableStatement cs = null; try { _log.info("...Calling: " + sql); conn = dataSource.getConnection(); conn.setAutoCommit(false); cs = conn.prepareCall(sql); final List<DfProcedureColumnMeta> boundColumnList = DfCollectionUtil.newArrayList(); setupBindParameter(conn, cs, columnList, testValueList, boundColumnList); boolean executed; try { executed = cs.execute(); } catch (SQLException e) { // retry without escape because Oracle sometimes hates escape final String retrySql = createSql(procedure, existsReturn, false); try { try { cs.close(); } catch (SQLException ignored) { } cs = conn.prepareCall(retrySql); setupBindParameter(conn, cs, columnList, testValueList, boundColumnList); executed = cs.execute(); _log.info(" (o) retry: " + retrySql); } catch (SQLException ignored) { _log.info(" (x) retry: " + retrySql); throw e; } } if (executed) { int closetIndex = 0; do { ResultSet rs = null; try { rs = cs.getResultSet(); if (rs == null) { break; } final Map<String, DfColumnMeta> columnMetaInfoMap = extractColumnMetaInfoMap(rs, sql); final DfProcedureNotParamResultMeta notParamResult = new DfProcedureNotParamResultMeta(); final String propertyName; if (procedure.isCalledBySelect() && closetIndex == 0) { // for example, table valued function // if the procedure of this type does not have // second or more result set basically // but checks closetIndex just in case propertyName = "returnResult"; } else { // basically here propertyName = "notParamResult" + (closetIndex + 1); } notParamResult.setPropertyName(propertyName); notParamResult.setResultSetColumnInfoMap(columnMetaInfoMap); procedure.addNotParamResult(notParamResult); ++closetIndex; } finally { closeResult(rs); } } while (cs.getMoreResults()); } int index = 0; for (DfProcedureColumnMeta column : boundColumnList) { final DfProcedureColumnType columnType = column.getProcedureColumnType(); if (DfProcedureColumnType.procedureColumnIn.equals(columnType)) { ++index; continue; } final int paramIndex = (index + 1); final Object obj; if (column.isPostgreSQLCursor()) { obj = _postgreSqlResultSetType.getValue(cs, paramIndex); } else if (column.isOracleCursor()) { obj = _oracleResultSetType.getValue(cs, paramIndex); } else { obj = cs.getObject(paramIndex); // as default } if (obj instanceof ResultSet) { ResultSet rs = null; try { rs = (ResultSet) obj; final Map<String, DfColumnMeta> columnMetaInfoMap = extractColumnMetaInfoMap(rs, sql); column.setResultSetColumnInfoMap(columnMetaInfoMap); } finally { closeResult(rs); } } ++index; } } catch (SQLException e) { final ExceptionMessageBuilder br = new ExceptionMessageBuilder(); br.addNotice("Failed to execute the procedure for getting meta data."); br.addItem("SQL"); br.addElement(sql); br.addItem("Parameter"); for (DfProcedureColumnMeta column : columnList) { br.addElement(column.getColumnDisplayName()); } br.addItem("Test Value"); br.addElement(buildTestValueDisp(testValueList)); br.addItem("Exception Message"); br.addElement(DfJDBCException.extractMessage(e)); SQLException nextEx = e.getNextException(); if (nextEx != null) { br.addElement(DfJDBCException.extractMessage(nextEx)); } final String msg = br.buildExceptionMessage(); final DfOutsideSqlProperties prop = getProperties().getOutsideSqlProperties(); if (prop.hasSpecifiedExecutionMetaProcedure()) { throw new DfProcedureExecutionMetaGettingFailureException(msg, e); } else { // if no specified, it continues _continuedFailureMessageMap.put(procedure.getProcedureFullQualifiedName(), msg); _log.info(msg); } } finally { if (cs != null) { cs.close(); } if (conn != null) { conn.rollback(); } } }
From source file:org.springframework.jdbc.core.JdbcTemplate.java
/** * Extract returned ResultSets from the completed stored procedure. * @param cs JDBC wrapper for the stored procedure * @param parameters Parameter list for the stored procedure * @return Map that contains returned results *//*w ww . j a v a2 s .c o m*/ protected Map extractReturnedResultSets(CallableStatement cs, List parameters, int updateCount) throws SQLException { Map returnedResults = new HashMap(); int rsIndex = 0; boolean moreResults; do { if (updateCount == -1) { Object param = null; if (parameters != null && parameters.size() > rsIndex) { param = parameters.get(rsIndex); } if (param instanceof SqlReturnResultSet) { SqlReturnResultSet rsParam = (SqlReturnResultSet) param; returnedResults.putAll(processResultSet(cs.getResultSet(), rsParam)); } else { logger.warn("ResultSet returned from stored procedure but a corresponding " + "SqlReturnResultSet parameter was not declared"); } rsIndex++; } moreResults = cs.getMoreResults(); updateCount = cs.getUpdateCount(); if (logger.isDebugEnabled()) { logger.debug("CallableStatement.getUpdateCount returned [" + updateCount + "]"); } } while (moreResults || updateCount != -1); return returnedResults; }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testNativeJdbcExtractorInvoked() throws Exception { MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); final ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.close();//from ww w .j a v a 2s .c o m ctrlResultSet.setVoidCallable(2); MockControl ctrlStatement = MockControl.createControl(Statement.class); final Statement mockStatement = (Statement) ctrlStatement.getMock(); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); MockControl ctrlStatement2 = MockControl.createControl(Statement.class); final Statement mockStatement2 = (Statement) ctrlStatement2.getMock(); mockStatement2.executeQuery("my query"); ctrlStatement2.setReturnValue(mockResultSet, 1); MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class); final PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock(); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); } mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); MockControl ctrlPreparedStatement2 = MockControl.createControl(PreparedStatement.class); final PreparedStatement mockPreparedStatement2 = (PreparedStatement) ctrlPreparedStatement2.getMock(); mockPreparedStatement2.executeQuery(); ctrlPreparedStatement2.setReturnValue(mockResultSet, 1); MockControl ctrlReturnResultSet = MockControl.createControl(ResultSet.class); final ResultSet mockReturnResultSet = (ResultSet) ctrlReturnResultSet.getMock(); mockReturnResultSet.next(); ctrlReturnResultSet.setReturnValue(false); mockReturnResultSet.close(); ctrlReturnResultSet.setVoidCallable(2); MockControl ctrlCallableStatement = MockControl.createControl(CallableStatement.class); final CallableStatement mockCallableStatement = (CallableStatement) ctrlCallableStatement.getMock(); if (debugEnabled) { mockCallableStatement.getWarnings(); ctrlCallableStatement.setReturnValue(null); } mockCallableStatement.close(); ctrlCallableStatement.setVoidCallable(); MockControl ctrlCallableStatement2 = MockControl.createControl(CallableStatement.class); final CallableStatement mockCallableStatement2 = (CallableStatement) ctrlCallableStatement2.getMock(); mockCallableStatement2.execute(); ctrlCallableStatement2.setReturnValue(true); mockCallableStatement2.getUpdateCount(); ctrlCallableStatement2.setReturnValue(-1); mockCallableStatement2.getResultSet(); ctrlCallableStatement2.setReturnValue(mockReturnResultSet); mockCallableStatement2.getMoreResults(); ctrlCallableStatement2.setReturnValue(false); mockCallableStatement2.getUpdateCount(); ctrlCallableStatement2.setReturnValue(-1); ctrlResultSet.replay(); ctrlStatement.replay(); ctrlStatement2.replay(); ctrlPreparedStatement.replay(); ctrlPreparedStatement2.replay(); ctrlReturnResultSet.replay(); ; ctrlCallableStatement.replay(); ctrlCallableStatement2.replay(); mockConnection.createStatement(); ctrlConnection.setReturnValue(mockStatement, 1); replay(); JdbcTemplate template = new JdbcTemplate(mockDataSource); template.setNativeJdbcExtractor(new NativeJdbcExtractor() { public boolean isNativeConnectionNecessaryForNativeStatements() { return false; } public boolean isNativeConnectionNecessaryForNativePreparedStatements() { return false; } public boolean isNativeConnectionNecessaryForNativeCallableStatements() { return false; } public Connection getNativeConnection(Connection con) { return con; } public Connection getNativeConnectionFromStatement(Statement stmt) throws SQLException { return stmt.getConnection(); } public Statement getNativeStatement(Statement stmt) { assertTrue(stmt == mockStatement); return mockStatement2; } public PreparedStatement getNativePreparedStatement(PreparedStatement ps) { assertTrue(ps == mockPreparedStatement); return mockPreparedStatement2; } public CallableStatement getNativeCallableStatement(CallableStatement cs) { assertTrue(cs == mockCallableStatement); return mockCallableStatement2; } public ResultSet getNativeResultSet(ResultSet rs) { return rs; } }); template.query("my query", new ResultSetExtractor() { public Object extractData(ResultSet rs2) { assertEquals(mockResultSet, rs2); return null; } }); template.query(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection conn) { return mockPreparedStatement; } }, new ResultSetExtractor() { public Object extractData(ResultSet rs2) { assertEquals(mockResultSet, rs2); return null; } }); template.call(new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection con) { return mockCallableStatement; } }, new ArrayList()); ctrlStatement.verify(); ctrlStatement2.verify(); ctrlPreparedStatement.verify(); ctrlPreparedStatement2.verify(); ctrlCallableStatement.verify(); ctrlCallableStatement2.verify(); }