Example usage for java.sql CallableStatement getString

List of usage examples for java.sql CallableStatement getString

Introduction

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

Prototype

String getString(String parameterName) throws SQLException;

Source Link

Document

Retrieves the value of a JDBC CHAR, VARCHAR, or LONGVARCHAR parameter as a String in the Java programming language.

Usage

From source file:com.mobilewallet.common.dao.ReferralIncentiveDAO.java

public Object[] addReferralIncetive(long userId, String refCode, String imei, String ip) {
    int added = 0;
    Connection connection = null;
    CallableStatement cstmt = null;
    String gcmId = null;//from   w  w  w . j ava2  s  .c om
    Object[] obj = null;
    try {
        connection = dataSource.getConnection();
        cstmt = connection.prepareCall("{call ADD_REFERRAL_CREDIT(?,?,?,?,?,?,?)}");
        cstmt.setLong(1, userId);
        cstmt.setString(2, refCode);
        cstmt.setString(3, imei);
        cstmt.setString(4, ip);
        cstmt.registerOutParameter(5, java.sql.Types.INTEGER);
        cstmt.registerOutParameter(6, java.sql.Types.VARCHAR);
        cstmt.registerOutParameter(7, java.sql.Types.VARCHAR);

        cstmt.execute();

        added = cstmt.getInt(5);
        gcmId = cstmt.getString(6);
        obj = new Object[3];
        obj[0] = added;
        obj[1] = gcmId;
        obj[2] = cstmt.getString(7);
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("Error in add referral incentive dao : " + ex.getMessage() + ", USER ID " + userId
                + ", refCode : " + refCode + ", imei : " + imei + ", IP : " + ip);
    } finally {
        try {
            if (cstmt != null) {
                cstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (Exception ex) {

        }
    }

    return obj;
}

From source file:org.wso2.ws.dataservice.DBUtils.java

private static String setOutparameterValue(CallableStatement cs, Query query, String resultSetFieldName)
        throws SQLException, AxisFault {
    // This could be an out parameter
    //Procedure returns both result & out parameters
    String elementValue = "";
    Param param = query.getParam(resultSetFieldName);
    if (param != null) {
        if ("OUT".equals(param.getType()) || "INOUT".equals(param.getType())) {
            if (param.getSqlType().equals(DBConstants.DataTypes.STRING)) {
                elementValue = cs.getString(param.getOrdinal());
            } else if (param.getSqlType().equals(DBConstants.DataTypes.DOUBLE)) {
                elementValue = String.valueOf(cs.getDouble(param.getOrdinal()));
            } else if (param.getSqlType().equals(DBConstants.DataTypes.BIGINT)) {
                elementValue = String.valueOf(cs.getLong(param.getOrdinal()));
            } else if (param.getSqlType().equals(DBConstants.DataTypes.INTEGER)) {
                elementValue = String.valueOf(cs.getInt(param.getOrdinal()));
            } else if (param.getSqlType().equals(DBConstants.DataTypes.TIME)) {
                elementValue = String.valueOf(cs.getTime(param.getOrdinal()));
            } else if (param.getSqlType().equals(DBConstants.DataTypes.DATE)) {
                elementValue = String.valueOf(cs.getDate(param.getOrdinal()));
            } else if (param.getSqlType().equals(DBConstants.DataTypes.TIMESTAMP)) {
                elementValue = String.valueOf(cs.getTimestamp(param.getOrdinal()));
            } else {
                log.error("Unsupported data type : " + param.getSqlType());
                throw new AxisFault("Unsupported data type : " + param.getSqlType());
            }//w  w w.j a va 2  s.  c  o  m

        }
    }
    return elementValue;
}

From source file:com.nextep.designer.sqlgen.oracle.debug.ctrl.DebugMethod.java

@Override
public Object invokeMethod(Object... arg) {

    IConnection conn = (IConnection) arg[0];

    CallableStatement stmt = null;
    Thread debuggedThread = null;
    try {/*from   w w w . jav  a 2  s .com*/
        // Initializing our target connection
        targetConn = CorePlugin.getConnectionService().connect(conn);
        //
        stmt = targetConn.prepareCall("ALTER SESSION SET PLSQL_DEBUG=TRUE"); //$NON-NLS-1$
        try {
            stmt.execute();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        stmt = targetConn.prepareCall("{ ? = CALL DBMS_DEBUG.INITIALIZE() }"); //$NON-NLS-1$
        try {
            stmt.registerOutParameter(1, Types.VARCHAR);
            stmt.execute();
            debugSessionID = stmt.getString(1);
        } catch (SQLException e) {
            throw new ErrorException(e);
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        // Switching to debug mode
        stmt = targetConn.prepareCall("{ CALL DBMS_DEBUG.DEBUG_ON() }"); //$NON-NLS-1$
        try {
            stmt.execute();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        // Starting our target code
        debuggedThread = new Thread(new TargetRunnable(targetConn));
        debuggedThread.start();

        // Now that we have our ID, we initialize debug connection
        debugConn = CorePlugin.getConnectionService().connect(conn);
        // new Thread(new DebugRunnable(debugConn,debugSessionID)).start();

        stmt = debugConn.prepareCall("{ CALL DBMS_DEBUG.ATTACH_SESSION(?) }"); //$NON-NLS-1$
        try {
            stmt.setString(1, debugSessionID);
            stmt.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

        stmt = debugConn.prepareCall("{ ? = CALL DBMS_DEBUG.SYNCHRONIZE(?,0) }"); //$NON-NLS-1$
        try {
            stmt.registerOutParameter(1, Types.INTEGER);
            stmt.registerOutParameter(2, OracleTypes.OTHER, "DBMS_DEBUG.RUNTIME_INFO"); //$NON-NLS-1$
            stmt.execute();
            Object o = stmt.getObject(2);
            if (o != null) {

            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }
        // // Setting breakpoints
        // stmt =
        // debugConn.prepareCall("{ call adp_debug.set_breakpoint(p_line=>?, p_name=>?, p_body=>true) }");
        // try {
        // for(IBreakpoint bp : SQLEditorUIServices.getInstance().getBreakpoints()) {
        // stmt.setInt(1, bp.getLine());
        // stmt.setString(2,bp.getTarget().getName());
        // stmt.execute();
        // }
        // } catch( Exception e) {
        // e.printStackTrace();
        // } finally {
        // stmt.close();
        // }
        stmt = debugConn.prepareCall("{ ? = CALL DBMS_DEBUG.CONTINUE(?,0,46) }"); //$NON-NLS-1$
        stmt.registerOutParameter(1, Types.INTEGER);
        stmt.registerOutParameter(2, OracleTypes.OTHER, "DBMS_DEBUG.RUNTIME_INFO"); //$NON-NLS-1$

        try {
            stmt.execute();
            Struct struct = (Struct) stmt.getObject(2);
            Object[] attrs = struct.getAttributes();
            int line = (Integer) attrs[0];
            int terminated = (Integer) attrs[1];
            int breakpoint = (Integer) attrs[2];
            LOGGER.debug(
                    "Continued to line " + line + ", terminated=" + terminated + ", breakpoint=" + breakpoint);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            CaptureHelper.safeClose(null, stmt);
        }

    } catch (SQLException e) {
        if (debuggedThread != null) {
            debuggedThread.interrupt();
        }
        throw new ErrorException(e);
    } finally {
        try {
            if (debugConn != null) {
                debugConn.close();
            }
        } catch (SQLException e) {
            throw new ErrorException("Unable to properly close connection: " + e.getMessage(), e);
        }
    }

    return null;
}

From source file:nl.nn.adapterframework.jdbc.XmlQuerySender.java

private String executeUpdate(Connection connection, String correlationID, String tableName, String query,
        Vector columns) throws SenderException {
    try {/*www  . jav a2  s  .c  o m*/
        if (existLob(columns)) {
            CallableStatement callableStatement = getCallWithRowIdReturned(connection, correlationID, query);
            applyParameters(callableStatement, columns);
            int ri = 1 + countParameters(columns);
            callableStatement.registerOutParameter(ri, Types.VARCHAR);
            callableStatement.setQueryTimeout(getTimeout());
            int numRowsAffected = callableStatement.executeUpdate();
            String rowId = callableStatement.getString(ri);
            log.debug(getLogPrefix() + "returning ROWID [" + rowId + "]");

            Iterator iter = columns.iterator();
            while (iter.hasNext()) {
                Column column = (Column) iter.next();
                if (column.getType().equalsIgnoreCase(TYPE_BLOB)
                        || column.getType().equalsIgnoreCase(TYPE_CLOB)) {
                    query = "SELECT " + column.getName() + " FROM " + tableName + " WHERE ROWID=?"
                            + " FOR UPDATE";
                    PreparedStatement statement = getStatement(connection, correlationID, query, true);
                    statement.setString(1, rowId);
                    statement.setQueryTimeout(getTimeout());
                    if (column.getType().equalsIgnoreCase(TYPE_BLOB)) {
                        executeUpdateBlobQuery(statement, column.getValue());
                    } else {
                        executeUpdateClobQuery(statement, column.getValue());
                    }
                }
            }
            return "<result><rowsupdated>" + numRowsAffected + "</rowsupdated></result>";
        }
        PreparedStatement statement = getStatement(connection, correlationID, query, false);
        applyParameters(statement, columns);
        statement.setQueryTimeout(getTimeout());
        return executeOtherQuery(connection, correlationID, statement, query, null, null);
    } catch (Throwable t) {
        throw new SenderException(t);
    }
}

From source file:com.rosy.bill.dao.hibernate.SimpleHibernateDao.java

@SuppressWarnings("deprecation")
public String callProc(final String proc, final List<Object> paramList, final int outIndex, final int outType) {
    String result = null;//from w  w w.j ava2 s. co  m
    java.sql.Connection conn = null;
    java.sql.CallableStatement cstmt = null;
    //Session session = this.getSession();
    try {

        conn = this.getSession().connection();
        conn.setAutoCommit(false);
        cstmt = conn.prepareCall(proc);
        for (int i = 0; paramList != null && i < paramList.size(); i++) {
            if (i + 1 == outIndex) {
                //cstmt.setInt(i + 1,
                //      (Integer.parseInt(paramList.get(i).toString())));
                cstmt.setString(i + 1, paramList.get(i).toString());
            } else {
                cstmt.setInt(i + 1, Integer.valueOf(paramList.get(i).toString()));
            }
        }
        cstmt.registerOutParameter(outIndex, outType);
        cstmt.execute();
        result = cstmt.getString(outIndex);
        conn.commit();
        //session.flush();
        //session.clear();
    } catch (Exception ex) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            logger.error("[" + proc + "]?" + e1.getMessage());
            e1.printStackTrace();
        }
        ex.printStackTrace();
    } finally {
        if (cstmt != null) {
            try {
                cstmt.close();
            } catch (Exception ex) {
            }
        }
    }
    return result;
}

From source file:Tim.MarkovChains.java

public String generate_markov(String type, int maxLength, int seedWord) {
    Connection con = null;//from ww w .j a  v a  2s. c  o m
    String sentence = "";
    try {
        con = db.pool.getConnection(timeout);
        CallableStatement nextSentenceStmt;

        if ("emote".equals(type)) {
            nextSentenceStmt = con.prepareCall("CALL generateMarkovEmote(?, ?)");
        } else {
            nextSentenceStmt = con.prepareCall("CALL generateMarkovSay(?, ?)");
        }

        nextSentenceStmt.registerOutParameter(2, java.sql.Types.LONGVARCHAR);

        int curWords = 0;

        while (curWords < maxLength) {
            nextSentenceStmt.setInt(1, seedWord);
            nextSentenceStmt.executeUpdate();
            String nextSentence = nextSentenceStmt.getString(2);

            if (seedWord > 0) {
                nextSentence = getMarkovWordById(seedWord) + " " + nextSentence;
            }

            if (nextSentence.split(" ").length >= 5) {
                seedWord = getSeedWord(nextSentence, type, seedWord);
            } else {
                seedWord = 0;
            }

            if ("emote".equals(type)) {
                if (curWords > 0) {
                    if (Tim.rand.nextInt(100) > 75) {
                        nextSentence = Tim.bot.getNick() + " " + nextSentence;
                    } else if (Tim.rand.nextInt(100) > 50) {
                        nextSentence = "He " + nextSentence;
                    } else {
                        nextSentence = "It " + nextSentence;
                    }
                }
            } else {
                nextSentence = StringUtils.capitalize(nextSentence);
            }

            if (!"".equals(sentence)) {
                nextSentence = " " + nextSentence;
            }

            if (!nextSentence.matches("[.?!\"']+$")) {
                String ending = ".";
                if (Tim.rand.nextInt(100) > 65) {
                    ending = sentenceEndings[Tim.rand.nextInt(sentenceEndings.length)];
                }

                nextSentence = nextSentence.replaceFirst("[.?!:;/\"'-]*$", ending);
            }

            curWords += nextSentence.trim().split("\\s+").length;
            sentence += nextSentence;

            // Odds of ending early = Percentage of Max divided by 4
            if (Tim.rand.nextInt(100) < ((1 - ((maxLength - curWords) / maxLength)) * 25)) {
                break;
            }
        }

        nextSentenceStmt.close();
    } catch (SQLException ex) {
        Logger.getLogger(Tim.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Tim.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    return sentence;
}

From source file:com.mobilewallet.common.dao.RegisterDAO.java

public Object[] registerUser(String email, String fname, String lname, String dob, String gender, String pwd,
        String imei, String accounts, String country, String handsetModel, String androidVer, String emulator,
        String gcmId, String androidId, String refCode, String ip, String fbId) {
    Object[] obj = null;/*from  www  .ja v  a  2s  .c om*/
    Connection con = null;
    CallableStatement cstmt = null;
    try {
        con = ds.getConnection();
        cstmt = con.prepareCall("{call REGISTER_USER(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
        cstmt.setString(1, email);
        cstmt.setString(2, fname);
        cstmt.setString(3, lname);
        cstmt.setString(4, dob);
        cstmt.setString(5, gender);
        cstmt.setString(6, pwd);
        cstmt.setString(7, imei);
        cstmt.setString(8, accounts);
        cstmt.setString(9, country);
        cstmt.setString(10, handsetModel);
        cstmt.setString(11, androidVer);
        cstmt.setString(12, emulator);
        cstmt.setString(13, gcmId);
        cstmt.setString(14, androidId);
        cstmt.setString(15, refCode);
        cstmt.setString(16, ip);
        cstmt.setString(17, fbId);
        cstmt.registerOutParameter(18, java.sql.Types.INTEGER);
        cstmt.registerOutParameter(19, java.sql.Types.VARCHAR);
        cstmt.registerOutParameter(20, java.sql.Types.INTEGER);
        cstmt.registerOutParameter(21, java.sql.Types.INTEGER);

        cstmt.execute();

        obj = new Object[4];
        obj[0] = cstmt.getInt(18);//rvalue
        obj[1] = cstmt.getString(19);//user ref code
        obj[2] = cstmt.getFloat(20);//balance
        obj[3] = cstmt.getLong(21);//user id
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (cstmt != null) {
                cstmt.close();
            }
        } catch (Exception ex) {

        }
        try {
            if (con != null) {
                con.close();
            }
        } catch (Exception ex) {

        }
    }
    return obj;
}

From source file:com.netspective.axiom.sql.StoredProcedureParameter.java

/**
 * Extract the OUT parameter values from the callable statment and
 * assign them to the value of the parameter.
 *//*from w  w w  .jav a 2  s  .  c o  m*/
public void extract(ConnectionContext cc, CallableStatement stmt) throws SQLException {
    if (getType().getValueIndex() == StoredProcedureParameter.Type.IN)
        return;

    int index = this.getIndex();
    QueryParameterType paramType = getSqlType();
    int jdbcType = paramType.getJdbcType();
    String identifier = paramType.getIdentifier();

    // result sets are special
    if (identifier.equals(QueryParameterType.RESULTSET_IDENTIFIER)) {
        ResultSet rs = (ResultSet) stmt.getObject(index);
        QueryResultSet qrs = new QueryResultSet(getParent().getProcedure(), cc, rs);
        value.getValue(cc).setValue(qrs);
        return;
    }

    switch (jdbcType) {
    case Types.VARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case Types.INTEGER:
        value.getValue(cc).setValue(new Integer(stmt.getInt(index)));
        break;
    case Types.DOUBLE:
        value.getValue(cc).setValue(new Double(stmt.getDouble(index)));
        break;
    case Types.CLOB:
        Clob clob = stmt.getClob(index);
        value.getValue(cc).setTextValue(clob.getSubString(1, (int) clob.length()));
        break;
    case java.sql.Types.ARRAY:
        Array array = stmt.getArray(index);
        value.getValue(cc).setValue(array);
        break;
    case java.sql.Types.BIGINT:
        long bigint = stmt.getLong(index);
        value.getValue(cc).setValue(new Long(bigint));
        break;
    case java.sql.Types.BINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.BIT:
        boolean bit = stmt.getBoolean(index);
        value.getValue(cc).setValue(new Boolean(bit));
    case java.sql.Types.BLOB:
        value.getValue(cc).setValue(stmt.getBlob(index));
        break;
    case java.sql.Types.CHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    case java.sql.Types.DATE:
        value.getValue(cc).setValue(stmt.getDate(index));
        break;
    case java.sql.Types.DECIMAL:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.DISTINCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.FLOAT:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    case java.sql.Types.JAVA_OBJECT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.LONGVARBINARY:
        value.getValue(cc).setTextValue(new String(stmt.getBytes(index)));
        break;
    case java.sql.Types.LONGVARCHAR:
        value.getValue(cc).setTextValue(stmt.getString(index));
        break;
    //case java.sql.Types.NULL:
    //    value.getValue(cc).setValue(null);
    //    break;
    case java.sql.Types.NUMERIC:
        value.getValue(cc).setValue(stmt.getBigDecimal(index));
        break;
    case java.sql.Types.OTHER:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.REAL:
        value.getValue(cc).setValue(new Float(stmt.getFloat(index)));
        break;
    //case java.sql.Types.REF:
    //    Ref ref = stmt.getRef(index);
    //    break;
    case java.sql.Types.SMALLINT:
        short sh = stmt.getShort(index);
        value.getValue(cc).setValue(new Short(sh));
        break;
    case java.sql.Types.STRUCT:
        value.getValue(cc).setValue(stmt.getObject(index));
        break;
    case java.sql.Types.TIME:
        value.getValue(cc).setValue(stmt.getTime(index));
        break;
    case java.sql.Types.TIMESTAMP:
        value.getValue(cc).setValue(stmt.getTimestamp(index));
        break;
    case java.sql.Types.TINYINT:
        byte b = stmt.getByte(index);
        value.getValue(cc).setValue(new Byte(b));
        break;
    case java.sql.Types.VARBINARY:
        value.getValue(cc).setValue(stmt.getBytes(index));
        break;
    default:
        throw new RuntimeException(
                "Unknown JDBC Type set for stored procedure parameter '" + this.getName() + "'.");
    }
}

From source file:org.nuclos.server.dblayer.impl.standard.StandardSqlDBAccess.java

protected <T> T getCallableResultValue(CallableStatement stmt, int index, Class<T> javaType)
        throws SQLException {
    Object value;// w w w.  j a  v  a  2s  .  com
    if (javaType == String.class) {
        value = stmt.getString(index);
    } else if (javaType == NuclosPassword.class) {
        value = new NuclosPassword(ServerCryptUtil.decrypt(stmt.getString(index)));
    } else if (javaType == Double.class) {
        value = stmt.getDouble(index);
    } else if (javaType == Long.class) {
        value = stmt.getLong(index);
    } else if (javaType == Integer.class) {
        value = stmt.getInt(index);
    } else if (javaType == Boolean.class) {
        value = stmt.getBoolean(index);
    } else if (javaType == BigDecimal.class) {
        value = stmt.getBigDecimal(index);
    } else if (javaType == java.util.Date.class) {
        value = stmt.getDate(index);
    } else if (javaType == byte[].class) {
        value = stmt.getBytes(index);
    } else if (javaType == NuclosScript.class) {
        final XStreamSupport xs = XStreamSupport.getInstance();
        final XStream xstream = xs.getXStream();
        try {
            value = xstream.fromXML(stmt.getString(index));
        } finally {
            xs.returnXStream(xstream);
        }
    } else {
        throw new IllegalArgumentException("Class " + javaType + " not supported by readField");
    }
    return stmt.wasNull() ? null : javaType.cast(value);
}

From source file:com.mobiaware.auction.data.impl.MySqlDataServiceImpl.java

@Override
public String signin(final int userUid) {
    Connection conn = null;//w  w  w.ja  v  a2 s . c om
    CallableStatement stmt = null;

    try {
        conn = _dataSource.getConnection();

        stmt = conn.prepareCall("{call SP_SIGNIN (?,?)}");
        stmt.setInt(1, userUid);
        stmt.registerOutParameter(2, Types.VARCHAR);

        stmt.execute();

        return stmt.getString(2);
    } catch (SQLException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        DbUtils.closeQuietly(conn, stmt, null);
    }

    return null;
}