Example usage for java.sql CallableStatement getResultSet

List of usage examples for java.sql CallableStatement getResultSet

Introduction

In this page you can find the example usage for java.sql CallableStatement getResultSet.

Prototype

ResultSet getResultSet() throws SQLException;

Source Link

Document

Retrieves the current result as a ResultSet object.

Usage

From source file:com.hangum.tadpole.sql.util.executer.procedure.MSSQLProcedureExecuter.java

@Override
public boolean exec(List<InOutParameterDAO> parameterList) throws Exception {
    initResult();// w w  w. jav a  2  s .com

    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:org.kawanfw.sql.servlet.sql.ServerCallableStatement.java

/**
 * Execute the passed SQL Statement and return: <br>
 * - The result set as a List of Maps for SELECT statements. <br>
 * - The return code for other statements
 * /*from w  w w  . ja v  a2s  .  c  om*/
 * @param sqlOrder
 *            the qsql order
 * @param sqlParms
 *            the sql parameters
 * @param out
 *            the output stream where to write to result set output
 * 
 * 
 * @throws SQLException
 */
private void callStatement(OutputStream out) throws SQLException, IOException {

    String sqlOrder = callableStatementHolder.getSqlOrder();

    debug("callableStatementHolder: " + callableStatementHolder.getSqlOrder());
    debug("sqlOrder               : " + sqlOrder);

    CallableStatement callableStatement = null;
    callableStatement = connection.prepareCall(sqlOrder);

    Map<Integer, Integer> parameterTypes = null;
    Map<Integer, String> parameterStringValues = null;

    // Class to set all the statement parameters
    ServerCallableStatementParameters serverCallableStatementParameters = null;

    try {

        ServerSqlUtilCallable.setCallableStatementProperties(callableStatement, callableStatementHolder);

        parameterTypes = callableStatementHolder.getParameterTypes();
        parameterStringValues = callableStatementHolder.getParameterStringValues();

        debug("before serverCallableStatementParameters");

        serverCallableStatementParameters = new ServerCallableStatementParameters(username, fileConfigurator,
                callableStatement, callableStatementHolder);
        serverCallableStatementParameters.setParameters();

        // Throws a SQL exception if the order is not authorized:
        debug("before new SqlSecurityChecker()");
        boolean isAllowedAfterAnalysis = true;

        /*
         * boolean isAllowedAfterAnalysis = sqlConfigurator
         * .allowStatementAfterAnalysis(username, connection, sqlOrder,
         * serverPreparedStatementParameters .getParameterValues());
         */
        if (!isAllowedAfterAnalysis) {

            String ipAddress = request.getRemoteAddr();
            SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress,
                    sqlOrder, serverCallableStatementParameters.getParameterValues());

            String message = Tag.PRODUCT_SECURITY + " [" + "{Callable Statement not authorized}"
                    + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}"
                    + "{sql values: " + parameterStringValues + "}]";

            throw new SecurityException(message);
        }

        isAllowedAfterAnalysis = SqlConfiguratorCall.allowResultSetGetMetaData(sqlConfigurator, username,
                connection);

        debug("before callableStatement.executeQuery() / execute");

        ServerSqlUtil.setMaxRowsToReturn(callableStatement, sqlConfigurator);

        ResultSet rs = null;
        boolean hasResultSet = false;

        if (isExecuteRaw) {
            hasResultSet = callableStatement.execute();
            if (hasResultSet) {
                rs = callableStatement.getResultSet();
            }
        } else {
            rs = callableStatement.executeQuery();
        }

        // 1) Update and send back the CallableStatementHolder:
        updateCallableStatementHolderValues(callableStatement);

        //out.write(TransferStatus.SEND_OK + CR_LF);
        ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);

        String jsonString = CallableStatementHolderTransportJson.toJson(callableStatementHolder);
        boolean doEncryptCallableStatement = SqlConfiguratorCall.encryptResultSet(sqlConfigurator);

        if (doEncryptCallableStatement) {
            jsonString = JsonLineEncrypter.encrypt(jsonString, commonsConfigurator);
        }

        //out.write(jsonString + CR_LF);
        ServerSqlManager.writeLine(out, jsonString);

        // 2) Send back the result set:

        if (hasResultSet || !isExecuteRaw) {
            try {

                // Horrible hack because ResultSetWriter is in common CE/EE
                // code and
                // we can't modify it now (to be clean in next CE version):
                StatementHolder statementHolder = new StatementHolder();
                statementHolder.setHtmlEncodingOn(callableStatementHolder.isHtmlEncodingOn());

                ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator,
                        fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder);

                resultSetWriter.write(rs);
            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        } else {
            // Write a line saying there is no Result Set!
            //out.write(CallableParms.NO_RESULT_SET + CR_LF);
            ServerSqlManager.writeLine(out, CallableParms.NO_RESULT_SET);
        }

    } catch (SQLException e) {
        ServerLogger.getLogger().log(Level.WARNING,
                Tag.PRODUCT_EXCEPTION_RAISED + CR_LF + "CallableStatement statement: " + sqlOrder + CR_LF
                        + "- sql order : " + sqlOrder + CR_LF + "- sql parms : " + parameterTypes + CR_LF
                        + "- sql values: " + parameterStringValues + CR_LF + "- exception : " + e.toString());
        throw e;
    } finally {
        // Close the ServerPreparedStatementParameters
        if (serverCallableStatementParameters != null) {
            serverCallableStatementParameters.close();
        }

        if (callableStatement != null) {
            callableStatement.close();
        }

        // Clean all
        parameterTypes = null;
        parameterStringValues = null;
        serverCallableStatementParameters = null;

    }
}

From source file:org.rimudb.storedproc.StoredProcedure.java

public List execute(boolean autoCommit) throws RimuDBException {
    ArrayList resultList = null;//from   w ww  .ja v a  2 s.  c o m
    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: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 .ja va2  s.  c om
 */
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.brucalipto.sqlutil.DB2SQLManager.java

/**
 * Method useful for using STORED PROCEDURE
 * @param spib The {@link SPInputBean} bean containing data to execute the stored procedure
 * @return The {@link SPOutputBean} containing returned values
 *///w  ww .  j a  v  a 2 s  . co  m
public SPOutputBean executeSP(final SPInputBean spib) throws SQLException {
    Connection conn = null;
    CallableStatement call = null;
    ResultSet resultSet = null;
    final String procedureName = spib.spName;

    SPParameter[] inputParameters = spib.inputParams;
    int[] outputParameters = spib.outputParams;

    final int inputParametersSize = inputParameters.length;
    final int outputParametersSize = outputParameters.length;

    final StringBuffer spName = new StringBuffer("call ").append(procedureName).append('(');
    int totalParameters = inputParametersSize + outputParametersSize;
    for (int i = 0; i < totalParameters; i++) {
        if (i != totalParameters - 1) {
            spName.append("?,");
        } else {
            spName.append('?');
        }
    }
    spName.append(")");

    try {
        if (this.dataSource != null) {
            conn = this.dataSource.getConnection();
        } else {
            conn = this.connection;
        }
        call = conn.prepareCall(spName.toString());
        for (int i = 0; i < inputParametersSize; i++) {
            final SPParameter inputParam = inputParameters[i];
            final int sqlType = inputParam.sqlType;
            final Object inputParamValue = inputParam.value;
            log.debug((i + 1) + ") Setting input value: " + inputParam);
            if (inputParamValue == null) {
                call.setNull(i + 1, sqlType);
                continue;
            }
            switch (sqlType) {
            case Types.VARCHAR:
                call.setString(i + 1, (String) inputParamValue);
                break;
            case Types.INTEGER:
                if (inputParamValue instanceof Integer) {
                    call.setInt(i + 1, ((Integer) inputParamValue).intValue());
                } else if (inputParamValue instanceof Long) {
                    call.setLong(i + 1, ((Long) inputParamValue).longValue());
                }
                break;
            case Types.DATE:
                call.setDate(i + 1, (Date) inputParamValue);
                break;
            case Types.BOOLEAN:
                call.setBoolean(i + 1, ((Boolean) inputParamValue).booleanValue());
                break;
            case Types.CHAR:
                call.setString(i + 1, ((Character) inputParamValue).toString());
                break;
            case Types.DOUBLE:
                call.setDouble(i + 1, ((Double) inputParamValue).doubleValue());
                break;
            case Types.FLOAT:
                call.setFloat(i + 1, ((Float) inputParamValue).floatValue());
                break;
            case Types.TIMESTAMP:
                call.setTimestamp(i + 1, (Timestamp) inputParamValue);
                break;
            default:
                call.setObject(i + 1, inputParamValue);
                break;
            }
        }

        for (int i = 0; i < outputParametersSize; i++) {
            int sqlType = outputParameters[i];
            log.debug((i + 1) + ") Registering output type 'Types."
                    + SQLUtilTypes.SQL_TYPES.get(Integer.valueOf("" + sqlType)) + "'");
            call.registerOutParameter(inputParametersSize + i + 1, sqlType);
        }

        log.debug("Going to call: '" + procedureName + "'");
        long elapsedTime = System.currentTimeMillis();
        boolean hasResultSet = call.execute();
        log.debug("SP '" + procedureName + "' executed in " + (System.currentTimeMillis() - elapsedTime)
                + "millis");
        if (hasResultSet) {
            log.debug("This SP is going to return also a resultSet");
        }

        final SPOutputBean output = new SPOutputBean();
        for (int i = 0; i < outputParametersSize; i++) {
            int sqlType = outputParameters[i];
            log.debug((i + 1) + ") Getting output type 'Types."
                    + SQLUtilTypes.SQL_TYPES.get(Integer.valueOf("" + sqlType)) + "'");
            final Object spResult = call.getObject(inputParametersSize + i + 1);
            SPParameter outParam = new SPParameter(sqlType, spResult);
            output.addResult(outParam);
        }
        if (hasResultSet) {
            RowSetDynaClass rowSetDynaClass = new RowSetDynaClass(call.getResultSet(), false);
            if (log.isDebugEnabled()) {
                log.debug("Going to return a RowSetDynaClass with following properties:");
                DynaProperty[] properties = rowSetDynaClass.getDynaProperties();
                for (int i = 0; i < properties.length; i++) {
                    log.debug("Name: '" + properties[i].getName() + "'; Type: '"
                            + properties[i].getType().getName() + "'");
                }
            }
            SPParameter outParam = new SPParameter(Types.JAVA_OBJECT, rowSetDynaClass);
            output.addResult(outParam);
        }
        return output;
    } finally {
        closeResources(resultSet, call, conn);
    }
}

From source file:org.executequery.databasemediators.spi.DefaultStatementExecutor.java

/** <p>Executes the specified procedure.
 *
 *  @param  the SQL procedure to execute
 *  @return the query result//from w w  w.  j  a va2s  .  com
 */
public SqlStatementResult execute(DatabaseExecutable databaseExecutable) throws SQLException {

    if (!prepared()) {

        return statementResult;
    }

    ProcedureParameter[] param = databaseExecutable.getParametersArray();
    Arrays.sort(param, new ProcedureParameterSorter());

    String procQuery = null;
    boolean hasOut = false;
    boolean hasParameters = (param != null && param.length > 0);

    List<ProcedureParameter> outs = null;
    List<ProcedureParameter> ins = null;

    if (hasParameters) {

        // split the params into ins and outs
        outs = new ArrayList<ProcedureParameter>();
        ins = new ArrayList<ProcedureParameter>();

        int type = -1;
        for (int i = 0; i < param.length; i++) {
            type = param[i].getType();
            if (type == DatabaseMetaData.procedureColumnIn || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the ins list
                ins.add(param[i]);

            } else if (type == DatabaseMetaData.procedureColumnOut
                    || type == DatabaseMetaData.procedureColumnResult
                    || type == DatabaseMetaData.procedureColumnReturn
                    || type == DatabaseMetaData.procedureColumnUnknown
                    || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the outs list
                outs.add(param[i]);

            }
        }

        char QUESTION_MARK = '?';
        String COMMA = ", ";

        // init the string buffer
        StringBuilder sb = new StringBuilder("{ ");
        if (!outs.isEmpty()) {

            // build the out params place holders
            for (int i = 0, n = outs.size(); i < n; i++) {

                sb.append(QUESTION_MARK);

                if (i < n - 1) {

                    sb.append(COMMA);
                }

            }

            sb.append(" = ");
        }

        sb.append(" call ");

        if (databaseExecutable.supportCatalogOrSchemaInFunctionOrProcedureCalls()) {

            String namePrefix = null;
            if (databaseExecutable.supportCatalogInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getCatalogName();

            }
            if (databaseExecutable.supportSchemaInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getSchemaName();

            }

            if (namePrefix != null) {

                sb.append(namePrefix).append('.');
            }
        }

        sb.append(databaseExecutable.getName()).append("( ");

        // build the ins params place holders
        for (int i = 0, n = ins.size(); i < n; i++) {
            sb.append(QUESTION_MARK);
            if (i < n - 1) {
                sb.append(COMMA);
            }
        }

        sb.append(" ) }");

        // determine if we have out params
        hasOut = !(outs.isEmpty());
        procQuery = sb.toString();
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("{ call ");

        if (databaseExecutable.getSchemaName() != null) {
            sb.append(databaseExecutable.getSchemaName()).append('.');
        }

        sb.append(databaseExecutable.getName()).append("( ) }");

        procQuery = sb.toString();
    }

    //Log.debug(procQuery);

    // null value literal
    String NULL = "null";

    // clear any warnings
    conn.clearWarnings();

    Log.info("Executing: " + procQuery);

    CallableStatement cstmnt = null;
    try {
        // prepare the statement
        cstmnt = conn.prepareCall(procQuery);
        stmnt = cstmnt;
    } catch (SQLException e) {
        handleException(e);
        statementResult.setSqlException(e);
        return statementResult;
    }

    // check if we are passing parameters
    if (hasParameters) {
        // the parameter index counter
        int index = 1;

        // the java.sql.Type value
        int dataType = -1;

        // the parameter input value
        String value = null;

        // register the out params
        for (int i = 0, n = outs.size(); i < n; i++) {
            //Log.debug("setting out at index: " + index);
            cstmnt.registerOutParameter(index, outs.get(i).getDataType());
            index++;
        }

        try {

            // register the in params
            for (int i = 0, n = ins.size(); i < n; i++) {

                ProcedureParameter procedureParameter = ins.get(i);
                value = procedureParameter.getValue();
                dataType = procedureParameter.getDataType();

                // try infer a type if OTHER
                if (dataType == Types.OTHER) {

                    // checking only for bit/bool for now

                    if (isTrueFalse(value)) {

                        dataType = Types.BOOLEAN;

                    } else if (isBit(value)) {

                        dataType = Types.BIT;
                        value = value.substring(2, value.length() - 1);
                    }

                }

                if (MiscUtils.isNull(value) || value.equalsIgnoreCase(NULL)) {

                    cstmnt.setNull(index, dataType);

                } else {

                    switch (dataType) {

                    case Types.TINYINT:
                        byte _byte = Byte.valueOf(value).byteValue();
                        cstmnt.setShort(index, _byte);
                        break;

                    case Types.SMALLINT:
                        short _short = Short.valueOf(value).shortValue();
                        cstmnt.setShort(index, _short);
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        cstmnt.setString(index, value);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:

                        boolean _boolean = false;
                        if (NumberUtils.isNumber(value)) {

                            int number = Integer.valueOf(value);
                            if (number > 0) {

                                _boolean = true;
                            }

                        } else {

                            _boolean = Boolean.valueOf(value).booleanValue();
                        }

                        cstmnt.setBoolean(index, _boolean);
                        break;

                    case Types.BIGINT:
                        long _long = Long.valueOf(value).longValue();
                        cstmnt.setLong(index, _long);
                        break;

                    case Types.INTEGER:
                        int _int = Integer.valueOf(value).intValue();
                        cstmnt.setInt(index, _int);
                        break;

                    case Types.REAL:
                        float _float = Float.valueOf(value).floatValue();
                        cstmnt.setFloat(index, _float);
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        cstmnt.setBigDecimal(index, new BigDecimal(value));
                        break;
                    /*
                                      case Types.DATE:
                                      case Types.TIMESTAMP:
                                      case Types.TIME:
                                        cstmnt.setTimestamp(index, new Timestamp( BigDecimal(value));
                    */
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        double _double = Double.valueOf(value).doubleValue();
                        cstmnt.setDouble(index, _double);
                        break;

                    default:
                        cstmnt.setObject(index, value);

                    }

                }

                // increment the index
                index++;
            }

        } catch (Exception e) {

            statementResult.setOtherErrorMessage(e.getClass().getName() + ": " + e.getMessage());
            return statementResult;
        }

    }

    /*
    test creating function for postgres:
            
    CREATE FUNCTION concat_lower_or_upper(a text, b text, uppercase boolean DEFAULT false)
    RETURNS text
    AS
    $$
     SELECT CASE
        WHEN $3 THEN UPPER($1 || ' ' || $2)
        ELSE LOWER($1 || ' ' || $2)
        END;
    $$
    LANGUAGE SQL IMMUTABLE STRICT;
    */

    try {
        cstmnt.clearWarnings();
        boolean hasResultSet = cstmnt.execute();
        Map<String, Object> results = new HashMap<String, Object>();

        if (hasOut) {
            // incrementing index
            int index = 1;

            // return value from each registered out
            String returnValue = null;

            for (int i = 0; i < param.length; i++) {

                int type = param[i].getType();
                int dataType = param[i].getDataType();

                if (type == DatabaseMetaData.procedureColumnOut
                        || type == DatabaseMetaData.procedureColumnResult
                        || type == DatabaseMetaData.procedureColumnReturn
                        || type == DatabaseMetaData.procedureColumnUnknown
                        || type == DatabaseMetaData.procedureColumnInOut) {

                    switch (dataType) {

                    case Types.TINYINT:
                        returnValue = Byte.toString(cstmnt.getByte(index));
                        break;

                    case Types.SMALLINT:
                        returnValue = Short.toString(cstmnt.getShort(index));
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        returnValue = cstmnt.getString(index);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:
                        returnValue = Boolean.toString(cstmnt.getBoolean(index));
                        break;

                    case Types.INTEGER:
                        returnValue = Integer.toString(cstmnt.getInt(index));
                        break;

                    case Types.BIGINT:
                        returnValue = Long.toString(cstmnt.getLong(index));
                        break;

                    case Types.REAL:
                        returnValue = Float.toString(cstmnt.getFloat(index));
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        returnValue = cstmnt.getBigDecimal(index).toString();
                        break;

                    case Types.DATE:
                    case Types.TIME:
                    case Types.TIMESTAMP:
                        returnValue = cstmnt.getDate(index).toString();
                        break;

                    case Types.FLOAT:
                    case Types.DOUBLE:
                        returnValue = Double.toString(cstmnt.getDouble(index));
                        break;

                    }

                    if (returnValue == null) {
                        returnValue = "NULL";
                    }

                    results.put(param[i].getName(), returnValue);
                    index++;
                }

            }

        }

        if (!hasResultSet) {

            statementResult.setUpdateCount(cstmnt.getUpdateCount());

        } else {

            statementResult.setResultSet(cstmnt.getResultSet());
        }

        useCount++;
        statementResult.setOtherResult(results);

    } catch (SQLException e) {

        statementResult.setSqlException(e);

    } catch (Exception e) {

        statementResult.setMessage(e.getMessage());
    }

    return statementResult;
}