Example usage for java.sql CallableStatement execute

List of usage examples for java.sql CallableStatement execute

Introduction

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

Prototype

boolean execute() throws SQLException;

Source Link

Document

Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

Usage

From source file:com.splicemachine.derby.utils.SpliceAdminIT.java

@Test
public void testUpdateSchemaOwner() throws Exception {
    String schemaName = "SPLICEADMINITSCHEMAFOO";
    String userName = "SPLICEADMINITUSERFRED";

    try {//  w w w .  j av  a 2s  .co m
        methodWatcher.executeUpdate(String.format("CREATE SCHEMA %s", schemaName));
    } catch (Exception e) {
        // Allow schema exists error
    }
    CallableStatement cs = null;
    try {
        cs = methodWatcher.prepareCall(
                String.format("call SYSCS_UTIL.SYSCS_CREATE_USER('%s', '%s')", userName, userName));
        cs.execute();
    } catch (Exception e) {
        // Allow user exists error
    } finally {
        DbUtils.closeQuietly(cs);
    }
    CallableStatement cs2 = null;
    ResultSet rs = null;
    try {
        cs2 = methodWatcher.prepareCall(
                String.format("call SYSCS_UTIL.SYSCS_UPDATE_SCHEMA_OWNER('%s', '%s')", schemaName, userName));
        cs2.execute();
        rs = methodWatcher.executeQuery(
                String.format("SELECT AUTHORIZATIONID FROM SYS.SYSSCHEMAS WHERE SCHEMANAME='%s'", schemaName));
        Assert.assertTrue(rs.next());
        Assert.assertEquals(userName, rs.getString(1));
    } finally {
        DbUtils.closeQuietly(rs);
    }
    try {
        methodWatcher.executeUpdate(String.format("DROP SCHEMA %s RESTRICT", schemaName));
    } catch (Exception e) {
        // Allow error
    }
}

From source file:com.mimp.hibernate.HiberMail.java

public ArrayList<Object> usuario2(String user, String pass) {

    org.hibernate.Session session = sessionFactory.getCurrentSession();

    final String usuario = user;
    final String password = pass;

    Work work = new Work() {
        @Override/*from   w w  w  .  ja va2  s  . com*/
        public void execute(Connection connection) throws SQLException {
            String query = "{call CONTRASENA(?, ?, ?, ?)}";
            CallableStatement statement = connection.prepareCall(query);
            statement.setString(1, usuario);
            statement.setString(2, password);
            statement.registerOutParameter(3, java.sql.Types.VARCHAR);
            statement.registerOutParameter(4, java.sql.Types.VARCHAR);
            statement.execute();

            String correo = statement.getString(3);
            String mensaje = statement.getString(4);
            temp.add(0, correo);
            temp.add(1, mensaje);
            statement.close();
        }
    };

    session.doWork(work);

    return temp;
}

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

public int resetPassword(String uuid, String userId, String password, String ip) {
    Connection connection = null;
    CallableStatement cstmt = null;
    int rvalue = -1;
    try {/*w w  w. j  a  va  2s  . com*/
        connection = dataSource.getConnection();
        cstmt = connection.prepareCall("{call wp_reset_pwd(?,?,?,?,?)}");
        cstmt.setString(1, userId);
        cstmt.setString(2, uuid);
        cstmt.setString(3, password);
        cstmt.setString(4, ip);
        cstmt.registerOutParameter(5, java.sql.Types.INTEGER);

        cstmt.execute();

        rvalue = cstmt.getInt(5);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

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

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

        }
    }
    return rvalue;
}

From source file:de.awtools.grooocle.varray.VarrayTest.java

@Test
public void testOraclesVarray() throws Exception {
    CallableStatement cs = null;
    try {// w w w .j  ava  2s . c o  m
        String arrayElements[] = { "Test3", "Test4", "Test5" };
        ArrayDescriptor desc = ArrayDescriptor.createDescriptor("T_STRING_VARRAY", conn);
        ARRAY newArray = new ARRAY(desc, conn, arrayElements);

        String spCall = "{ call call_me(?, ?) }";
        cs = conn.prepareCall(spCall);
        cs.setArray(1, newArray);
        cs.registerOutParameter(2, java.sql.Types.INTEGER);

        cs.execute();
        assertEquals(3, cs.getInt(2));
    } finally {
        if (cs != null) {
            cs.close();
        }
    }

}

From source file:com.aw.core.dao.DAOSql.java

protected void dbmsOutputPrint(Connection conn, StringBuffer buf) throws java.sql.SQLException {
    String getLineSql = "begin dbms_output.get_line(?,?); end;";
    CallableStatement stmt = conn.prepareCall(getLineSql);
    boolean hasMore = true;
    stmt.registerOutParameter(1, Types.VARCHAR);
    stmt.registerOutParameter(2, Types.INTEGER);
    while (hasMore) {
        boolean status = stmt.execute();
        hasMore = (stmt.getInt(2) == 0);
        if (hasMore) {
            buf.append(stmt.getString(1)).append("\n");
        }/*  ww  w .jav a 2 s  .co m*/
    }
    stmt.close();
}

From source file:eionet.cr.util.virtuoso.VirtuosoJdbcDriverTest.java

/**
 * Test if CR uses correct Virtuoso JDBC driver. It shouldn't get "Too many open statements" error.
 *
 * @throws SQLException When problem with connecting to Virtuoso.
 *//*w w w.  ja v a  2  s.  c  om*/
@Test
public void testTooManyOpenStmts() throws SQLException {

    VirtuosoConnectionPoolDataSource dbsource = new VirtuosoConnectionPoolDataSource();

    String testDbURI = GeneralConfig.getRequiredProperty(GeneralConfig.VIRTUOSO_DB_URL);
    URI uri = URI.create(testDbURI.substring(5));

    dbsource.setServerName(uri.getHost());
    dbsource.setPortNumber(uri.getPort());
    dbsource.setPassword(GeneralConfig.getRequiredProperty(GeneralConfig.VIRTUOSO_DB_PWD));
    dbsource.setUser(GeneralConfig.getRequiredProperty(GeneralConfig.VIRTUOSO_DB_USR));
    dbsource.setCharset("UTF-8");
    VirtuosoPooledConnection pooledConnection = (VirtuosoPooledConnection) dbsource.getPooledConnection();
    virtuoso.jdbc4.VirtuosoConnection con = pooledConnection.getVirtuosoConnection();
    String jdbcComp = "DB.DBA.TTLP (?, ?, ?, ?)";
    CallableStatement stmt = null;
    int MAXIT = 10000;
    for (int i = 0; i < MAXIT; i++) {
        try {
            stmt = con.prepareCall(jdbcComp);
            stmt.setString(1, "");
            stmt.setString(2, "");
            stmt.setString(3, DUMMY_GRAPH_URI);
            stmt.setInt(4, 256);
            stmt.execute();
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            fail("can't add data to virtuoso. ");
        } finally {
            if (stmt != null) {
                stmt.close();
            }
        }
    }
}

From source file:net.solarnetwork.node.dao.jdbc.derby.DerbyCompressTableJob.java

@Override
protected void executeInternal(JobExecutionContext jobContext) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Compressing Derby table " + schema + '.' + table + " with purgeRows = " + purgeRows
                + ", defragmentRows = " + defragmentRows + ", truncateEnd = " + truncateEnd);
    }//w  ww. j  a v a2 s . co m
    jdbcOperations.execute(new CallableStatementCreator() {
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
            if (log.isTraceEnabled()) {
                log.trace("Preparing Derby compress table call [" + COMPRESS_CALL + ']');
            }
            return con.prepareCall(COMPRESS_CALL);
        }
    }, new CallableStatementCallback<Object>() {
        public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
            int idx = 1;
            cs.setString(idx++, schema);
            cs.setString(idx++, table);
            cs.setShort(idx++, purgeRows ? (short) 1 : (short) 0);
            cs.setShort(idx++, defragmentRows ? (short) 1 : (short) 0);
            cs.setShort(idx++, truncateEnd ? (short) 1 : (short) 0);
            boolean result = cs.execute();
            if (log.isTraceEnabled()) {
                log.trace("Derby compress table call returned [" + result + ']');
            }
            return null;
        }
    });
    if (log.isInfoEnabled()) {
        log.info("Compressed Derby table " + schema + '.' + table);
    }
}

From source file:com.oracle.tutorial.jdbc.StoredProcedureJavaDBSample.java

public void runStoredProcedures(String coffeeNameArg, double maximumPercentageArg, double newPriceArg)
        throws SQLException {
    CallableStatement cs = null;

    try {//  ww  w .  ja v  a  2  s .  c om

        System.out.println("\nCalling the stored procedure GET_SUPPLIER_OF_COFFEE");
        cs = this.con.prepareCall("{call GET_SUPPLIER_OF_COFFEE(?, ?)}");
        cs.setString(1, coffeeNameArg);
        cs.registerOutParameter(2, Types.VARCHAR);
        cs.execute();

        String supplierName = cs.getString(2);

        if (supplierName != null) {
            System.out.println("\nSupplier of the coffee " + coffeeNameArg + ": " + supplierName);
        } else {
            System.out.println("\nUnable to find the coffee " + coffeeNameArg);
        }

        System.out.println("\nCalling the procedure SHOW_SUPPLIERS");
        cs = this.con.prepareCall("{call SHOW_SUPPLIERS()}");
        ResultSet rs = cs.executeQuery();

        while (rs.next()) {
            String supplier = rs.getString("SUP_NAME");
            String coffee = rs.getString("COF_NAME");
            System.out.println(supplier + ": " + coffee);
        }

        System.out.println("\nContents of COFFEES table before calling RAISE_PRICE:");
        CoffeesTable.viewTable(this.con);

        System.out.println("\nCalling the procedure RAISE_PRICE");
        cs = this.con.prepareCall("{call RAISE_PRICE(?,?,?)}");
        cs.setString(1, coffeeNameArg);
        cs.setDouble(2, maximumPercentageArg);
        cs.registerOutParameter(3, Types.DOUBLE);
        cs.setDouble(3, newPriceArg);

        cs.execute();

        System.out.println("\nValue of newPrice after calling RAISE_PRICE: " + cs.getFloat(3));

        System.out.println("\nContents of COFFEES table after calling RAISE_PRICE:");
        CoffeesTable.viewTable(this.con);

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (cs != null) {
            cs.close();
        }
    }
}

From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageHandler.java

public SqlMessage handleMessage(final SqlMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    DataSource ds = appCtx.getBean(msg.getDatasource(), DataSource.class);
    JdbcTemplate tmpl = new JdbcTemplate(ds);

    String sql = msg.getSql();//from   w w w . ja  v a2 s.  c om
    CallableStatementCreator stmtCreator = null;
    CallableStatementCallback<SqlMessage> callback = null;
    if (sql.startsWith("plugin:")) {
        // Use a plugin to get the sql
        String pluginName = (sql.contains("?") ? sql.substring(7, sql.indexOf('?')) : sql.substring(7));
        final Plugin plugin = groovyPluginManager.getPlugin(pluginName);
        Map<String, Object> vars = new LinkedHashMap<String, Object>();
        vars.put("message", msg);
        vars.put("datasource", ds);
        vars.put("listen", groovyClosureFactory.createListenClosure(msg));
        vars.put("mapreduce", groovyClosureFactory.createMapReduceClosure(msg));
        plugin.setContext(vars);

        // Execute this plugin
        plugin.run();

        Object o = plugin.get("sql");
        if (null != o && o instanceof Closure) {
            sql = ((Closure) o).call(msg).toString();
        } else if (o instanceof String || o instanceof GString) {
            sql = o.toString();
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to SQL statement.");
        }
        msg.setSql(sql);

        o = plugin.get("statementCreator");
        if (null != o && o instanceof Closure) {
            stmtCreator = new CallableStatementCreator() {
                public CallableStatement createCallableStatement(Connection con) throws SQLException {
                    Object obj = ((Closure) plugin.get("statementCreator")).call(new Object[] { con, msg });
                    log.debug("from plugin statementCreator: " + String.valueOf(obj));
                    return (CallableStatement) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCreator. Define a closure named 'statementCreator' in your plugin.");
        }

        o = plugin.get("callback");
        if (null != o && o instanceof Closure) {
            callback = new CallableStatementCallback<SqlMessage>() {
                public SqlMessage doInCallableStatement(CallableStatement cs)
                        throws SQLException, DataAccessException {
                    Object obj = ((Closure) plugin.get("callback")).call(new Object[] { cs, msg });
                    log.debug("from plugin callback: " + String.valueOf(obj));
                    return (SqlMessage) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCallback. Define a closure named 'callback' in your plugin.");
        }
    } else {
        stmtCreator = new CallableStatementCreator() {
            public CallableStatement createCallableStatement(Connection connection) throws SQLException {
                CallableStatement stmt = connection.prepareCall(msg.getSql());
                List<Object> params = msg.getParams();
                if (null != params) {
                    int index = 1;
                    for (Object obj : params) {
                        stmt.setObject(index++, obj);
                    }
                }
                return stmt;
            }
        };
        callback = new CallableStatementCallback<SqlMessage>() {
            public SqlMessage doInCallableStatement(CallableStatement callableStatement)
                    throws SQLException, DataAccessException {
                if (null == msg.getResults().getData()) {
                    msg.getResults().setData(new ArrayList<List<Object>>());
                }
                if (callableStatement.execute()) {
                    ResultSet results = callableStatement.getResultSet();

                    // Pull out column names
                    ResultSetMetaData meta = results.getMetaData();
                    String[] columns = new String[meta.getColumnCount()];
                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                        columns[i - 1] = meta.getColumnName(i);
                    }
                    msg.getResults().getColumnNames().addAll(Arrays.asList(columns));

                    int total = 0;
                    while (results.next()) {
                        List<Object> row = new ArrayList<Object>(columns.length);
                        for (int i = 1; i <= columns.length; i++) {
                            row.add(results.getObject(i));
                        }
                        msg.getResults().getData().add(row);
                        total++;
                    }
                    msg.getResults().setTotalRows(total);

                } else {
                    msg.getResults().getColumnNames().add("updateCount");
                    msg.getResults().setTotalRows(1);
                    List<Object> updCnt = new ArrayList<Object>(1);
                    updCnt.add(callableStatement.getUpdateCount());
                    msg.getResults().getData().add(updCnt);
                }
                return msg;
            }
        };
    }
    try {
        tmpl.setExceptionTranslator(appCtx.getBean(SQLExceptionTranslator.class));
    } catch (NoSuchBeanDefinitionException notfound) {
        // IGNORED
    }

    if (null != stmtCreator && null != callback) {
        try {
            tmpl.execute(stmtCreator, callback);
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            List<String> errors = new ArrayList<String>();
            errors.add(t.getMessage());
            Throwable cause = t.getCause();
            if (null != cause) {
                do {
                    errors.add(cause.getMessage());
                } while (null != (cause = cause.getCause()));
            }
            msg.getResults().setErrors(errors);
        }
    } else {
        log.warn("CallableStatementCreator and/or CallableStatementCallback where empty. "
                + "Make sure your plugin provides these under 'statementCreator' and 'callback' respectively.");
    }
    return msg;
}

From source file:com.mobilewallet.credits.dao.CreditsDAO.java

public int updateCredits(long userId, String isCorrect, int position) {
    int updated = 0;
    Connection connection = null;
    CallableStatement cstmt = null;
    try {// ww w .ja v a 2  s.  c  om
        connection = dataSource.getConnection();
        cstmt = connection.prepareCall("{call update_credits_proc(?,?,?,?)}");
        cstmt.setLong(1, userId);
        cstmt.setString(2, isCorrect);
        cstmt.setInt(3, position);
        cstmt.registerOutParameter(4, java.sql.Types.INTEGER);
        cstmt.execute();

        updated = cstmt.getInt(4);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

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

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

        }
    }
    return updated;
}