List of usage examples for java.sql CallableStatement getResultSet
ResultSet getResultSet() throws SQLException;
ResultSet
object. From source file:org.executequery.databasemediators.spi.DefaultStatementExecutor.java
/** <p>Executes the specified procedure and returns * a <code>ResultSet</code> object from this query. * <p>If an exception occurs, null is returned and * the relevant error message, if available, assigned * to this object for retrieval./*from w w w. jav a 2 s. c o m*/ * * @param the SQL procedure to execute * @return the query result */ private SqlStatementResult executeProcedure(String query) throws SQLException { if (!prepared()) { return statementResult; } //Log.debug("query " + query); String execString = "EXECUTE "; String callString = "CALL "; int nameIndex = -1; int index = query.toUpperCase().indexOf(execString); // check if EXECUTE was entered if (index != -1) { nameIndex = execString.length(); } else { // must be CALL nameIndex = callString.length(); } String procedureName = null; // check for input brackets boolean possibleParams = false; index = query.indexOf("(", nameIndex); if (index != -1) { possibleParams = true; procedureName = query.substring(nameIndex, index); } else { procedureName = query.substring(nameIndex); } String prefix = prefixFromName(procedureName); procedureName = suffixFromName(procedureName); DatabaseHost host = new DatabaseObjectFactoryImpl().createDatabaseHost(databaseConnection); if (prefix == null) { prefix = host.getDefaultNamePrefix(); } DatabaseExecutable procedure = host.getDatabaseSource(prefix).getProcedure(procedureName); if (procedure == null) { // hedge procedure = host.getDatabaseSource(prefix).getFunction(procedureName); } if (procedure != null) { if (possibleParams) { String params = query.substring(index + 1, query.indexOf(")")); if (!MiscUtils.isNull(params)) { // check that the proc accepts params // if (!procedure.hasParameters()) { // // statementResult.setSqlException(new SQLException("Procedure call was invalid")); // return statementResult; // } int paramIndex = 0; ProcedureParameter[] parameters = procedure.getParametersArray(); // extract the parameters StringTokenizer st = new StringTokenizer(params, ","); // no defined params from the meta data but params supplied ?? // attempt to execute as supplied and bubble up db error if an issue if (parameters.length == 0) { parameters = new ProcedureParameter[st.countTokens()]; for (int i = 0, n = st.countTokens(); i < n; i++) { procedure.addParameter("UNKNOWN", DatabaseMetaData.procedureColumnIn, Types.OTHER, "OTHER", -1); } parameters = procedure.getParametersArray(); } while (st.hasMoreTokens()) { String value = st.nextToken().trim(); // check applicable param for (int i = paramIndex; i < parameters.length; i++) { paramIndex++; int type = parameters[i].getType(); if (type == DatabaseMetaData.procedureColumnIn || type == DatabaseMetaData.procedureColumnInOut) { // check the data type and remove quotes if char int dataType = parameters[i].getDataType(); if (dataType == Types.CHAR || dataType == Types.VARCHAR || dataType == Types.LONGVARCHAR) { if (value.indexOf("'") != -1) { // assuming quotes at start and end value = value.substring(1, value.length() - 1); } } parameters[i].setValue(value); break; } } } } } // execute the procedure return execute(procedure); } else { // just run it... CallableStatement cstmnt = null; try { cstmnt = conn.prepareCall(query); boolean hasResultSet = cstmnt.execute(); if (!hasResultSet) { statementResult.setUpdateCount(cstmnt.getUpdateCount()); } else { statementResult.setResultSet(cstmnt.getResultSet()); } } catch (SQLException e) { handleException(e); statementResult.setSqlException(e); } return statementResult; /* statementResult.setSqlException( new SQLException("Procedure or Function name specified is invalid")); return statementResult; */ } }
From source file:com.novartis.opensource.yada.adaptor.JDBCAdaptor.java
/** * Executes the statemetns stored in the query object. Results are * stored in a data structure inside a {@link YADAQueryResult} object * contained by the query object./*from w ww.j a va 2 s . c o m*/ * @since 4.0.0 * @param yq {@link YADAQuery} object containing code to be executed * @throws YADAAdaptorExecutionException when the adaptor can't execute the statement or statements stored in the query */ @Override public void execute(YADAQuery yq) throws YADAAdaptorExecutionException { l.debug("Executing query [" + yq.getQname() + "]"); boolean count = Boolean.valueOf(yq.getYADAQueryParamValue(YADARequest.PS_COUNT)[0]).booleanValue(); boolean countOnly = Boolean.valueOf(yq.getYADAQueryParamValue(YADARequest.PS_COUNTONLY)[0]).booleanValue(); int countResult = -1; int dataSize = yq.getData().size() > 0 ? yq.getData().size() : 1; for (int row = 0; row < dataSize; row++) { yq.setResult(); YADAQueryResult yqr = yq.getResult(); if (yq.getType().equals(Parser.CALL)) { CallableStatement c = yq.getCstmt(row); for (int i = 0; i < yq.getParamCount(row); i++) { int position = i + 1; char dt = yq.getDataTypes(row)[i]; String val = yq.getVals(row).get(i); try { setQueryParameter(c, position, dt, val); } catch (YADASQLException e) { String msg = "There was an issue building the JDBC/SQL statement"; throw new YADAAdaptorExecutionException(msg, e); } } boolean hasData = false; try { hasData = c.execute(); } catch (SQLException e) { String msg = "CallableStatement failed to execute"; throw new YADAAdaptorExecutionException(msg, e); } ResultSet resultSet = null; if (hasData) { try { resultSet = c.getResultSet(); } catch (SQLException e) { String msg = "Unable to get ResultSet from CallableStatement"; throw new YADAAdaptorExecutionException(msg, e); } } else { resultSet = new YADAResultSet(); } yqr.addResult(row, resultSet); if (count) { try { while (resultSet.next()) { countResult++; } } catch (SQLException e) { String msg = "There was a problem iterating through the CallableStatement's ResultSet for row count."; throw new YADAAdaptorExecutionException(msg, e); } yqr.addCountResult(row, new Integer(countResult)); } } else // SELECT, UPDATE, INSERT, DELETE { PreparedStatement p = yq.getPstmt(row); for (int i = 0; i < yq.getParamCount(row); i++) { int position = i + 1; char dt = yq.getDataTypes(row)[i]; String val = yq.getVals(row).get(i); try { setQueryParameter(p, position, dt, val); } catch (YADASQLException e) { String msg = "There was an issue building the JDBC/SQL statement"; throw new YADAAdaptorExecutionException(msg, e); } } if (yq.getType().equals(Parser.SELECT)) { ResultSet resultSet = null; try { if (!countOnly) { resultSet = p.executeQuery(); yqr.addResult(row, resultSet); } } catch (SQLException e) { String msg = "PreparedStatement for data failed to execute."; throw new YADAAdaptorExecutionException(msg, e); } if (count || countOnly) { p = yq.getPstmtForCount(p); for (int i = 0; i < yq.getParamCount(row); i++) { int position = i + 1; char dt = yq.getDataTypes(row)[i]; String val = yq.getVals(row).get(i); try { setQueryParameter(p, position, dt, val); } catch (YADASQLException e) { String msg = "There was an issue building the JDBC/SQL statement"; throw new YADAAdaptorExecutionException(msg, e); } } try { resultSet = p.executeQuery(); } catch (SQLException e) { String msg = "PreparedStatement for row count failed to execute."; throw new YADAAdaptorExecutionException(msg, e); } try { while (resultSet.next()) { countResult = resultSet.getInt(SQL_COUNT); } } catch (SQLException e) { String msg = "There was a problem iterating over ResultSet for row count."; throw new YADAAdaptorExecutionException(msg, e); } yqr.addCountResult(row, new Integer(countResult)); } } else // UPDATE, INSERT, DELETE { try { countResult = p.executeUpdate(); } catch (SQLException e) { String msg = "Prepared statement for update failed to execute"; throw new YADAAdaptorExecutionException(msg, e); } yqr.addCountResult(row, new Integer(countResult)); } } } }
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;//w ww . ja v a 2s . 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:com.wabacus.system.dataset.select.rationaldbassistant.GetDataSetBySP.java
protected Object doGetResultSet(SPDataSetValueBean spBean, Object typeObj, StringBuffer systemParamsBuf) { log.debug(systemParamsBuf.toString()); String procedure = spBean.getProcedure(); if (rbean.getInterceptor() != null) { Object obj = rbean.getInterceptor().beforeLoadData(rrequest, rbean, typeObj, procedure); if (!(obj instanceof String)) { return obj; }//w w w .j a va 2 s .c o m procedure = (String) obj; } if (Config.show_sql) log.info("Execute sql: " + procedure); CallableStatement cstmt = null; try { cstmt = rrequest.getConnection(spBean.getOwnerSpProvider().getDatasource()).prepareCall(procedure); AbsDatabaseType dbtype = rrequest.getDbType(spBean.getOwnerSpProvider().getDatasource()); VarcharType varcharObj = (VarcharType) Config.getInstance().getDataTypeByClass(VarcharType.class); int idx = 1; if (spBean.getLstStoreProcedureParams() != null && spBean.getLstStoreProcedureParams().size() > 0) { for (String paramTmp : spBean.getLstStoreProcedureParams()) { if (WabacusAssistant.getInstance().isGetRequestContextValue(paramTmp)) {//request/session? varcharObj.setPreparedStatementValue(idx, WabacusAssistant.getInstance().getRequestContextStringValue(rrequest, paramTmp, ""), cstmt, dbtype); } else if (Tools.isDefineKey("condition", paramTmp)) { setConditionValue(rrequest, spBean, cstmt, dbtype, idx, Tools.getRealKeyByDefine("condition", paramTmp), varcharObj); } else { varcharObj.setPreparedStatementValue(idx, paramTmp, cstmt, dbtype); } idx++; } } if (spBean.getOwnerSpProvider().isUseSystemParams()) { if (systemParamsBuf == null) systemParamsBuf = new StringBuffer(); cstmt.setString(idx++, systemParamsBuf.toString());//?? } if (dbtype instanceof Oracle) { cstmt.registerOutParameter(idx, OracleTypes.CURSOR); } rrequest.addUsedStatement(cstmt); cstmt.executeQuery(); ResultSet rs = null; if (dbtype instanceof Oracle) { rs = (ResultSet) cstmt.getObject(idx); } else { rs = cstmt.getResultSet(); } return rs; } catch (SQLException e) { throw new WabacusRuntimeException( "??" + rbean.getPath() + "?SQL" + procedure + "", 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 v a 2 s .c o m*/ 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: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 av a 2 s.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(); }
From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java
private ResultSet getFirstRSOfStoredProc(CallableStatement stmt) throws SQLException { boolean resultAndNoUpdateCount = stmt.execute(); ResultSet result = null;// w w w . ja v a 2 s. c om while (true) { if (!resultAndNoUpdateCount) { if (stmt.getUpdateCount() == -1) { break; } } else { result = stmt.getResultSet(); break; } try { resultAndNoUpdateCount = stmt.getMoreResults(Statement.KEEP_CURRENT_RESULT); } catch (SQLException e) { /* * for some DBMS, this will throw an unsupported feature * exception, even when after a valid result set is retrieved * first, so if there's a valid result set existing, we will * ignore the eventual unsupported feature exception */ if (result == null) { throw e; } break; } } return result; }
From source file:cc.tooyoung.common.db.JdbcTemplate.java
/** * Extract output parameters 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 w w .j ava 2 s. c om @SuppressWarnings("unchecked") protected Map extractOutputParameters(CallableStatement cs, List parameters) throws SQLException { Map returnedResults = new HashMap(); int sqlColIndex = 1; for (int i = 0; i < parameters.size(); i++) { SqlParameter param = (SqlParameter) parameters.get(i); if (param instanceof SqlOutParameter) { SqlOutParameter outParam = (SqlOutParameter) param; if (outParam.isReturnTypeSupported()) { Object out = outParam.getSqlReturnType().getTypeValue(cs, sqlColIndex, outParam.getSqlType(), outParam.getTypeName()); returnedResults.put(outParam.getName(), out); } else { Object out = cs.getObject(sqlColIndex); if (out instanceof ResultSet) { if (outParam.isResultSetSupported()) { returnedResults.putAll(processResultSet((ResultSet) out, outParam)); } else { String rsName = outParam.getName(); SqlReturnResultSet rsParam = new SqlReturnResultSet(rsName, new ColumnMapRowMapper()); returnedResults.putAll(processResultSet(cs.getResultSet(), rsParam)); ApiLogger.info("Added default SqlReturnResultSet parameter named " + rsName); } } else { returnedResults.put(outParam.getName(), out); } } } if (!(param.isResultsParameter())) { sqlColIndex++; } } return returnedResults; }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testExecuteClosed() throws Exception { MockControl ctrlResultSet;//ww w .j a v a 2 s.co m ResultSet mockResultSet; MockControl ctrlCallable; CallableStatement mockCallable; ctrlResultSet = MockControl.createControl(ResultSet.class); mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.close(); ctrlResultSet.setVoidCallable(); ctrlCallable = MockControl.createControl(CallableStatement.class); mockCallable = (CallableStatement) ctrlCallable.getMock(); mockCallable.execute(); ctrlCallable.setReturnValue(true); mockCallable.getUpdateCount(); ctrlCallable.setReturnValue(-1); mockCallable.getResultSet(); ctrlCallable.setReturnValue(mockResultSet); mockCallable.close(); ctrlCallable.setVoidCallable(); mockConnection.prepareCall("my query"); ctrlConnection.setReturnValue(mockCallable); ctrlResultSet.replay(); ctrlCallable.replay(); replay(); List params = new ArrayList(); params.add(new SqlReturnResultSet("", new RowCallbackHandler() { public void processRow(ResultSet rs) { throw new InvalidDataAccessApiUsageException(""); } })); JdbcTemplate template = new JdbcTemplate(mockDataSource); try { template.call(new CallableStatementCreator() { public CallableStatement createCallableStatement(Connection conn) throws SQLException { return conn.prepareCall("my query"); } }, params); } catch (InvalidDataAccessApiUsageException idaauex) { // ok } // verify confirms if test is successful by checking if close() called ctrlResultSet.verify(); ctrlCallable.verify(); }
From source file:com.wabacus.system.dataset.sqldataset.GetDataSetByStoreProcedure.java
private ResultSet doGetResultSet(ReportRequest rrequest, ReportBean rbean, ReportDataSetValueBean datasetbean, Object typeObj, StringBuffer systemParamsBuf) { log.debug(systemParamsBuf.toString()); String procedure = datasetbean.getValue(); if (rbean.getInterceptor() != null) { Object obj = rbean.getInterceptor().beforeLoadData(rrequest, rbean, typeObj, procedure); if (obj == null) return null; if (obj instanceof List || obj instanceof ResultSet) { throw new WabacusRuntimeException("" + rbean.getPath() + "????ResultSetList"); }/* w w w. j a v a 2s. com*/ if (!(obj instanceof String)) { throw new WabacusRuntimeException( "" + rbean.getPath() + "??" + obj.getClass().getName() + "??"); } procedure = (String) obj; } if (Config.show_sql) { log.info("Execute sql: " + procedure); } CallableStatement cstmt = null; try { cstmt = rrequest.getConnection(datasetbean.getDatasource()).prepareCall(procedure); AbsDatabaseType dbtype = rrequest.getDbType(datasetbean.getDatasource()); VarcharType varcharObj = (VarcharType) Config.getInstance().getDataTypeByClass(VarcharType.class); int idx = 1; if (datasetbean.getLstStoreProcedureParams() != null && datasetbean.getLstStoreProcedureParams().size() > 0) { ConditionBean cbeanTmp; for (String paramTmp : datasetbean.getLstStoreProcedureParams()) { if (WabacusAssistant.getInstance().isGetRequestContextValue(paramTmp)) {//request/session? varcharObj.setPreparedStatementValue(idx, WabacusAssistant.getInstance().getRequestContextStringValue(rrequest, paramTmp, ""), cstmt, dbtype); } else if (Tools.isDefineKey("condition", paramTmp)) { cbeanTmp = rbean.getSbean() .getConditionBeanByName(Tools.getRealKeyByDefine("condition", paramTmp)); if (cbeanTmp.getIterator() > 1 || cbeanTmp.getCcolumnsbean() != null || cbeanTmp.getCvaluesbean() != null) { varcharObj.setPreparedStatementValue(idx, cbeanTmp.getConditionValueForSP(rrequest), cstmt, dbtype); } else { cbeanTmp.getDatatypeObj().setPreparedStatementValue(idx, cbeanTmp.getConditionValueForSP(rrequest), cstmt, dbtype); } } else { varcharObj.setPreparedStatementValue(idx, paramTmp, cstmt, dbtype); } idx++; } } cstmt.setString(idx++, systemParamsBuf.toString()); if (dbtype instanceof Oracle) { cstmt.registerOutParameter(idx, OracleTypes.CURSOR); } rrequest.addUsedStatement(cstmt); cstmt.executeQuery(); ResultSet rs = null; if (dbtype instanceof Oracle) { rs = (ResultSet) cstmt.getObject(idx); } else { rs = cstmt.getResultSet(); } return rs; } catch (SQLException e) { throw new WabacusRuntimeException( "??" + rbean.getPath() + "?SQL" + procedure + "", e); } }