Example usage for java.sql Statement executeBatch

List of usage examples for java.sql Statement executeBatch

Introduction

In this page you can find the example usage for java.sql Statement 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:org.sipfoundry.sipxconfig.admin.dialplan.AttendantMigrationContextImpl.java

private void cleanSchema() {
    try {/*from  w ww  .ja va  2 s  . c o  m*/
        Session currentSession = getHibernateTemplate().getSessionFactory().getCurrentSession();
        Connection connection = currentSession.connection();
        Statement statement = connection.createStatement();
        for (int i = 0; i < SQL.length; i++) {
            statement.addBatch(SQL[i]);
        }
        statement.executeBatch();
        statement.close();
    } catch (SQLException e) {
        LOG.warn("cleaning schema", e);
    }
}

From source file:com.cyclopsgroup.tornado.hibernate.taglib.ExecuteSqlsTagBase.java

/**
 * Override method processTag in class CreateTablesTag
 *
 * @see com.cyclopsgroup.waterview.utils.TagSupportBase#processTag(org.apache.commons.jelly.XMLOutput)
 *//*from w  ww.  j av a2s . c om*/
protected void processTag(XMLOutput output) throws Exception {
    HibernateTag hibernate = (HibernateTag) requireInside(HibernateTag.class);
    String[] sqls = getSqls(hibernate);
    Connection dbcon = hibernate.getConnection();
    Statement s = dbcon.createStatement();
    if (isBatched()) {
        for (int i = 0; i < sqls.length; i++) {
            s.addBatch(sqls[i]);
        }
        try {
            s.executeBatch();
        } catch (Exception e) {
            logger.debug("Dropping table error", e);
        }
    } else {
        for (int i = 0; i < sqls.length; i++) {
            try {
                s.execute(sqls[i]);
            } catch (Exception e) {
                logger.debug("Dropping table error", e);
            }
        }
    }
    s.close();
}

From source file:de.unidue.inf.is.ezdl.dlbackend.AbstractBackendTestBase.java

/**
 * Creates tables in the test database.//from   w w w . j  a v a  2  s  .co m
 * 
 * @param createTableStatementsResourceName
 */
protected final void createTables(String createTableStatementsResourceName) {
    Connection connection = null;
    try {
        InputStream is = getClass().getResourceAsStream(createTableStatementsResourceName);
        String createTableStatements = IOUtils.toString(is, "UTF-8");
        String[] createTableStatementsArray = createTableStatements.split("\\n\\s*\\n");
        connection = provider.connection();
        Statement st = connection.createStatement();
        for (String createTableStatement : createTableStatementsArray) {
            st.addBatch(createTableStatement);
        }
        st.executeBatch();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        ClosingUtils.close(connection);
    }
}

From source file:wzw.util.DbUtils.java

/**
 * ??./*from ww  w  .j  av a2  s.co  m*/
 * @param conn ?
 * @param allsql ?sql??
 * @throws ?
 * @return ?sql???
 */
public static int[] executeBatch(List<String> list, Connection conn) throws SQLException {

    //?
    if (conn == null || conn.isClosed()) {
        throw new SQLException("Connection Object is null or is closed!");
    }

    Statement stmt = null;
    int returns[];
    boolean isConnCreated = false;
    try {
        if (conn == null || conn.isClosed()) { // ????
            conn = getConnection(); //?????? 
            isConnCreated = true;
        }

        stmt = conn.createStatement();
        addBatch(stmt, list);
        returns = stmt.executeBatch();

        if (isConnCreated) {
            conn.commit(); //?????
        }
        return returns;
        //log.debug("doUpdate commit success!");

    } catch (SQLException e) {
        if (isConnCreated) {
            conn.rollback(); //?????
        }

        String info = "Result in doBatch Exception'SQLs is:";
        for (int i = 0; i < list.size(); i++) {
            info += list.get(i).toString() + ";";
        }
        log.fatal(DbUtils.class.getName() + " " + e.getMessage() + ". " + info);
        log.debug("debug", e);
        /// e.pri ntStackTrace();
        throw e;

    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException e) {
            log.fatal("DBUtils.doBatch() ?\n", e);
            log.debug("debug", e);
            /// e.pri ntStackTrace();
        }

        try {
            if (isConnCreated && conn != null)
                conn.close(); //?????

        } catch (SQLException e) {
            log.fatal("DBUtils.doBatch() ?\n", e);
            log.debug("debug", e);
            /// e.pri ntStackTrace();
        }
    }
    // return null;
}

From source file:org.apache.sqoop.manager.sqlserver.MSSQLTestUtils.java

public void populateLineItem() {
    String sql = "insert into tpch1m_lineitem values (1,2,3,4,5,6,7,8,'AB',"
            + "'CD','abcd','efgh','hijk','dothis','likethis','nocomments')";
    String sql2 = "insert into tpch1m_lineitem values (2,3,4,5,6,7,8,9,'AB'"
            + ",'CD','abcd','efgh','hijk','dothis','likethis','nocomments')";
    String sql3 = "insert into tpch1m_lineitem values (3,4,5,6,7,8,9,10,'AB',"
            + "'CD','abcd','efgh','hijk','dothis','likethis','nocomments')";
    String sql4 = "insert into tpch1m_lineitem values (4,5,6,7,8,9,10,11,'AB'"
            + ",'CD','abcd','efgh','hijk','dothis','likethis','nocomments')";
    Connection dbcon = this.getConnection();
    Statement st;
    try {//from w  w  w . j  a v  a 2s  .  co m
        st = dbcon.createStatement();
        st.addBatch(sql);
        st.addBatch(sql2);
        st.addBatch(sql3);
        st.addBatch(sql4);
        int[] res = st.executeBatch();

        System.out.println(res);
    } catch (SQLException e) {
        LOG.error(StringUtils.stringifyException(e));
    }

}

From source file:org.rti.zcore.dar.utils.DatabaseUtils.java

/**
 * Execute sql batch file with line-break-separated statements
 * @param conn/*from w  ww.  j  a v  a  2s.c om*/
 * @param statements
 * @return
 * @throws Exception
 */
public static int[] executeQueryBatch(Connection conn, String statements) throws Exception {

    int[] updateCounts;
    try {
        Statement s = conn.createStatement();
        String[] sqlArray = statements.split("\n");
        for (int i = 0; i < sqlArray.length; i++) {
            String sql = sqlArray[i];
            s.addBatch(sql);
        }
        updateCounts = s.executeBatch();
        s.clearBatch();
        s.close();
    } catch (Exception ex) {
        log.info("Sql: " + statements);
        log.error(ex);
        throw new ServletException("Cannot retrieve results:", ex);
    }
    return updateCounts;
}

From source file:com.zionex.t3sinc.util.db.SincDatabaseUtility.java

public int[] executeBatch(Statement statement, List sqlStrings) throws SQLException {
    for (Iterator iterator = sqlStrings.iterator(); iterator.hasNext();) {
        statement.addBatch(iterator.next().toString());
    }//from   w ww.  ja v  a 2s.c  o m
    return statement.executeBatch();
}

From source file:org.xmetdb.rest.protocol.db.user.test.User_crud_test.java

License:asdf

@Override
protected IQueryUpdate<T, DBUser> createQuery() throws Exception {
    IDatabaseConnection c = getConnection();
    Statement st = c.getConnection().createStatement();
    st.addBatch("USE aalocal_test;");
    st.addBatch("DELETE FROM aalocal_test.users;");
    st.addBatch("DELETE FROM aalocal_test.user_registration;");
    st.addBatch("DELETE FROM aalocal_test.user_roles;");
    st.executeBatch();
    ITable table = c.createQueryTable("EXPECTED", String.format("SELECT user_name from aalocal_test.users"));
    Assert.assertEquals(0, table.getRowCount());
    table = c.createQueryTable("EXPECTED",
            String.format("SELECT user_name from aalocal_test.user_registration"));
    Assert.assertEquals(0, table.getRowCount());
    table = c.createQueryTable("EXPECTED", String.format("SELECT role_name from aalocal_test.user_roles"));
    Assert.assertEquals(0, table.getRowCount());
    st.close();/*from  ww  w  .  java  2  s.c  o  m*/
    c.close();

    DBUser user = new DBUser();
    user.setFirstname("QWERTY");
    user.setLastname("ASDFG");
    user.setUserName("testuser");
    user.setCredentials(new UserCredentials(null, "test"));
    return (IQueryUpdate<T, DBUser>) new CreateUser(user, new UserRegistration(code), "aalocal_test");
}

From source file:it.attocchi.db.JdbcConnector.java

/**
 * //from   w w w  .  j a v  a 2  s.  c  om
 * @param aQuery
 * @param params
 * @return
 * @throws SQLException
 */
public int executeBatchUpdate(boolean keepConnOpen, List<String> batchQuery) throws Exception {
    int res = 0;

    try {

        if (ListUtils.isNotEmpty(batchQuery)) {

            logger.debug(batchQuery.size());

            Connection connection = getConnection();

            // connection.setAutoCommit(false);

            Statement statement = connection.createStatement();
            for (String aQuery : batchQuery) {
                statement.addBatch(aQuery);
            }

            int[] counts = statement.executeBatch();

            for (int count : counts) {
                res = res + count;
            }
            // connection.commit();
        }

    } finally {
        if (!keepConnOpen)
            close();
    }

    return res;
}

From source file:com.gdo.project.util.SqlUtils.java

@Deprecated
public static void batchUpdate(StclContext stclContext, String[] queries) throws SQLException {
    Connection con = null;/*from w  ww. j  av a  2  s.c om*/
    Statement stmt = null;
    try {
        con = getConnection(stclContext);
        stmt = con.createStatement();
        for (String query : queries) {
            if (!StringUtils.isEmpty(query))
                stmt.addBatch(query);
        }
        stmt.executeBatch();
    } finally {
        if (stmt != null)
            closeStatement(stclContext, stmt);
    }
}