Example usage for java.sql CallableStatement executeBatch

List of usage examples for java.sql CallableStatement executeBatch

Introduction

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

Prototype

int[] executeBatch() throws SQLException;

Source Link

Document

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Usage

From source file:com.medlog.webservice.util.ToneAnalyzerExample.java

public static void processTone(DbConnection dbc, ToneAnalysis tone, int diaryID) {
    CallableStatement cs = null;
    String cat_id = "";
    try {/*from w w w.  j  a v a2  s .c  o m*/
        //category , tone , sentance,score,text
        List<ToneCategory> to = tone.getDocumentTone().getTones();
        Connection conn = dbc.getConnnection();

        conn.prepareCall(new StringBuilder().append("{call spDiaryTextScoreInsert(").append(diaryID)
                .append(",?,?,?,?,?)}").toString());
        conn.setAutoCommit(false);
        cs.setInt(3, 0);
        cs.setNull(5, java.sql.Types.NVARCHAR);// cat_id);

        for (ToneCategory docTC : to) {
            cat_id = docTC.getId();
            cs.setString(1, cat_id);
            for (ToneScore s : docTC.getTones()) {
                cs.setString(2, s.getId());
                cs.setDouble(4, s.getScore());
                cs.addBatch();
            }
            int[] docRes = cs.executeBatch();
            cs.clearBatch();
            System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result --- "
                    + ArrayUtils.toString(docRes));
        }
        System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() Process "
                + tone.getSentencesTone().size() + " sentances.");
        for (SentenceTone sentT : tone.getSentencesTone()) {
            to = sentT.getTones();
            cs.setInt(3, sentT.getId());
            cs.setString(5, toS(sentT.getText()).trim());
            for (ToneCategory docTC : to) {
                cat_id = docTC.getId();
                cs.setString(1, cat_id);
                for (ToneScore s : docTC.getTones()) {
                    cs.setString(2, s.getId());
                    cs.setDouble(4, s.getScore());
                    cs.addBatch();
                }
                int[] docRes = cs.executeBatch();
                cs.clearBatch();
                System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result["
                        + sentT.getId() + "] " + ArrayUtils.toString(docRes));
            }
        }

    } catch (SQLException ex) {
        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.medlog.webservice.services.tone.ToneProcessorFactory.java

private static ArrayList<Integer> processTone(DbConnection dbc, ToneAnalysis tone, int diaryID) {
    CallableStatement cs = null;
    String cat_id = "";
    ArrayList<Integer> results = new ArrayList<Integer>();
    try {//from w w w . ja  va 2 s.c  o  m
        //category , tone , sentance,score,text
        List<com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory> to = tone.getDocumentTone()
                .getTones();
        Connection conn = dbc.getConnnection();

        cs = conn.prepareCall(new StringBuilder().append("{call spDiaryTextScoreInsert(").append(diaryID)
                .append(",?,?,?,?,?)}").toString());
        conn.setAutoCommit(false);
        cs.setInt(3, 0);
        cs.setNull(5, java.sql.Types.NVARCHAR);// cat_id);

        for (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory docTC : to) {
            cat_id = docTC.getId();
            cs.setString(1, cat_id);
            for (ToneScore s : docTC.getTones()) {
                cs.setString(2, s.getId());
                cs.setDouble(4, s.getScore());
                cs.addBatch();
            }

        }
        System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() Process "
                + tone.getSentencesTone().size() + " sentances.");
        int[] docRes = cs.executeBatch();
        List l = Arrays.asList(docRes);
        results.addAll(l);

        cs.clearBatch();
        System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result --- "
                + ArrayUtils.toString(docRes));
        int[] sentRes = null;
        for (SentenceTone sentT : tone.getSentencesTone()) {
            to = sentT.getTones();
            cs.setInt(3, sentT.getId());
            cs.setString(5, toS(sentT.getText()).trim());
            for (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory docTC : to) {
                cat_id = docTC.getId();
                cs.setString(1, cat_id);

                try {
                    for (ToneScore s : docTC.getTones()) {
                        cs.setString(2, s.getId());
                        cs.setDouble(4, s.getScore());
                        cs.addBatch();
                    }
                    if (DEBUG) {
                        DbUtl.getWarningsFromStatement(cs);
                    }
                    //                        sentRes = cs.executeBatch();
                    //                        List l = Arrays.asList(sentRes);
                    //                        results.addAll(l);
                } catch (SQLException s) {
                    System.err.println(
                            "com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(loop)"
                                    + DbUtl.printJDBCExceptionMsg(s));
                    s.printStackTrace();
                } catch (Exception s) {

                }

                System.out.println("com.medlog.webservice.util.ToneAnalyzerExample.processTone() result["
                        + sentT.getId() + "] " + ArrayUtils.toString(sentRes));
            }
        }
        sentRes = cs.executeBatch();
        try {
            l = Arrays.asList(sentRes);
            results.addAll(l);
            conn.setAutoCommit(true);
            cs.clearBatch();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.setAutoCommit(true);
            } catch (Exception eeee) {
                eeee.printStackTrace();
            }
        }
    } catch (BatchUpdateException ex) {
        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(batch)"
                + DbUtl.printBatchUpdateException(ex));

    } catch (SQLTimeoutException ex) {

        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    } catch (SQLException ex) {
        Logger.getLogger(ToneAnalyzerExample.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println("com.medlog.webservice.services.tone.ToneProcessorFactory.processTone(meth)"
                + DbUtl.printJDBCExceptionMsg(ex));

    } finally {
        DbUtl.close(cs);
    }
    return results;
}

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

/**
 * NOTE: When using the batch update facility, a CallableStatement object can call only stored
 * procedures that take input parameters or no parameters at all. Further, the stored procedure
 * must return an update count. The CallableStatement.executeBatch method
 * (inherited from PreparedStatement) will throw a BatchUpdateException if the stored procedure
 * returns anything other than an update count or takes OUT or INOUT parameters.
 *//*  w  w  w . ja v  a  2s . c  o m*/
protected int[] batchExecute(ConnectionContext cc) throws SQLException, NamingException {
    // TODO: This method NEEDS to be tested!
    Connection conn;
    CallableStatement stmt;

    conn = cc.getConnection();
    String sql = StringUtils.strip(getSqlText(cc));

    stmt = conn.prepareCall(sql);
    // TODO: parameters must do addBatch() calles!!!
    if (parameters != null)
        parameters.apply(cc, stmt);

    return stmt.executeBatch();

}

From source file:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java

private Object processPreStoredProcQuery(InternalParamCollection params, int queryLevel)
        throws DataServiceFault {
    boolean isError = false;
    CallableStatement stmt = null;
    ResultSet rs = null;/*from  ww w.  jav  a 2s .co m*/
    try {
        Connection conn = this.createConnection(queryLevel);
        stmt = (CallableStatement) this.createProcessedPreparedStatement(SQLQuery.DS_QUERY_TYPE_STORED_PROC,
                params, conn);
        /* check if this is a batch request */
        if (this.isJDBCFirstBatchRequest()) {
            this.setBatchPreparedStatement(stmt);
            /* add this to cleanup this query after batch request */
            BatchDataServiceRequest.addParticipant(this);
        }
        if (!this.hasResult() || (this.hasResult() && this.isReturnGeneratedKeys())
                || (this.hasResult() && this.isReturnUpdatedRowCount())) {
            /* if we are in the middle of a batch request, don't execute it */
            if (this.isJDBCBatchRequest()) {
                /* if this is the last one, execute the full batch */
                if (this.isJDBCLastBatchRequest()) {
                    stmt.executeBatch();
                }
            } else {
                stmt.executeUpdate();
            }
        } else {
            /*
             * check if all the result elements are out params; if so, no
             * result set
             */
            if (this.isResultOnlyOutParams()) {
                stmt.execute();
                /* if there's a ref cursor, get the result set */
                if (this.hasRefCursor()) {
                    rs = (ResultSet) stmt.getObject(getCurrentRefCursorOrdinal());
                }
            } else {
                rs = this.getFirstRSOfStoredProc(stmt);
            }
        }
        return new QueryResultInfo(stmt, rs);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        isError = true;
        throw new DataServiceFault(e, FaultCodes.DATABASE_ERROR,
                "Error in 'SQLQuery.processStoredProcQuery': " + e.getMessage());
    } finally {
        if (isError) {
            this.releaseResources(rs, this.isStatementClosable(isError) ? stmt : null);
        }
    }
}