Example usage for java.sql Statement execute

List of usage examples for java.sql Statement execute

Introduction

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

Prototype

boolean execute(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may return multiple results.

Usage

From source file:com.taobao.datax.plugins.writer.pgsqlwriter.PgsqlWriter.java

@Override
public int startWrite(LineReceiver receiver) {
    com.mysql.jdbc.Statement stmt = null;
    try {/*from w w w  . ja va2  s.  c  o  m*/

        this.connection = DBSource.getConnection(this.sourceUniqKey);
        stmt = (com.mysql.jdbc.Statement) ((org.apache.commons.dbcp.DelegatingConnection) this.connection)
                .getInnermostDelegate()
                .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        /* set max count */
        this.logger.info(String.format("Config max_error_count: set max_error_count=%d", MAX_ERROR_COUNT));
        stmt.executeUpdate(String.format("set max_error_count=%d;", MAX_ERROR_COUNT));

        /* set connect encoding */
        this.logger.info(String.format("Config encoding %s .", this.encoding));
        for (String sql : this.makeLoadEncoding(encoding))
            stmt.execute(sql);

        /* load data begin */
        String loadSql = this.makeLoadSql();
        this.logger.info(String.format("Load sql: %s.", visualSql(loadSql)));

        PgsqlWriterInputStreamAdapter localInputStream = new PgsqlWriterInputStreamAdapter(receiver, this);
        stmt.setLocalInfileInputStream(localInputStream);
        stmt.executeUpdate(visualSql(loadSql));
        this.lineCounter = localInputStream.getLineNumber();

        this.logger.info("DataX write to mysql ends .");

        return PluginStatus.SUCCESS.value();
    } catch (Exception e2) {
        if (null != this.connection) {
            try {
                this.connection.close();
            } catch (SQLException e) {
            }
        }
        throw new DataExchangeException(e2.getCause());
    } finally {
        if (null != stmt)
            try {
                stmt.close();
            } catch (SQLException e3) {
            }
    }
}

From source file:com.taobao.datax.plugins.writer.sqlserverwriter.SqlserverWriter.java

@Override
public int startWrite(LineReceiver receiver) {
    com.mysql.jdbc.Statement stmt = null;
    try {/*from ww w.jav a  2s  .c  o  m*/

        this.connection = DBSource.getConnection(this.sourceUniqKey);
        stmt = (com.mysql.jdbc.Statement) ((org.apache.commons.dbcp.DelegatingConnection) this.connection)
                .getInnermostDelegate()
                .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        /* set max count */
        this.logger.info(String.format("Config max_error_count: set max_error_count=%d", MAX_ERROR_COUNT));
        stmt.executeUpdate(String.format("set max_error_count=%d;", MAX_ERROR_COUNT));

        /* set connect encoding */
        this.logger.info(String.format("Config encoding %s .", this.encoding));
        for (String sql : this.makeLoadEncoding(encoding))
            stmt.execute(sql);

        /* load data begin */
        String loadSql = this.makeLoadSql();
        this.logger.info(String.format("Load sql: %s.", visualSql(loadSql)));

        SqlserverWriterInputStreamAdapter localInputStream = new SqlserverWriterInputStreamAdapter(receiver,
                this);
        stmt.setLocalInfileInputStream(localInputStream);
        stmt.executeUpdate(visualSql(loadSql));
        this.lineCounter = localInputStream.getLineNumber();

        this.logger.info("DataX write to mysql ends .");

        return PluginStatus.SUCCESS.value();
    } catch (Exception e2) {
        if (null != this.connection) {
            try {
                this.connection.close();
            } catch (SQLException e) {
            }
        }
        throw new DataExchangeException(e2.getCause());
    } finally {
        if (null != stmt)
            try {
                stmt.close();
            } catch (SQLException e3) {
            }
    }
}

From source file:com.aurel.track.dbase.InitDatabase.java

private static void insertNullObjectsAndSampleData() {
    ResultSet rs = null;//from   w w  w .  j av  a 2  s  .  c o m
    Connection coni = null;
    Connection cono = null;
    try {
        coni = getConnection();
        cono = getConnection();
        Statement istmt = coni.createStatement();
        Statement ostmt = cono.createStatement();
        LOGGER.info("Testing for NULL objects...");
        // --------------- T S I T E ----------------------
        rs = istmt.executeQuery("SELECT * FROM TSITE");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TSITE " + "(OBJECTID) " + "VALUES (1)");
                LOGGER.info("Inserted TSITE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting TSITE object: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        // --------------- T P R O J E C T T Y P E ----------------------
        rs = istmt.executeQuery("SELECT * FROM TPROJECTTYPE WHERE OBJECTID = 0");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute(
                        "INSERT INTO TPROJECTTYPE " + "(OBJECTID, LABEL, NOTIFYOWNERLEVEL, NOTIFYMANAGERLEVEL) "
                                + "VALUES (0, 'Generic Space', 0, 1)");
                LOGGER.info("Inserted NULL project (PKEY = 0) into TPROJECTTYPE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TPROJECTTYPE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        rs = istmt.executeQuery("SELECT * FROM TPROJECTTYPE WHERE OBJECTID = -1");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TPROJECTTYPE " + "(OBJECTID, LABEL, DEFAULTFORPRIVATE) "
                        + "VALUES (-1, 'Private Project', 'Y')");
                LOGGER.info("Inserted Private project (PKEY = -1) into TPROJECTTYPE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting private space in TPROJECTTYPE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        rs = istmt.executeQuery("SELECT * FROM TPROJECT WHERE PKEY = 0");
        // ------------------- T P R O J E C T  -----------------------
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TPROJECT " + "(PKEY, LABEL, DEFOWNER, DEFMANAGER, PROJECTTYPE) "
                        + "VALUES (0, 'Generic Space', 1, 1, 0)");
                LOGGER.info("Inserted NULL project (PKEY = 0) into TPROJECT");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TPROJECT: " + exc.getMessage());
            }
        }

        // ----------------------- T R O L E ------------------------------
        rs = istmt.executeQuery("SELECT * FROM TROLE WHERE PKEY = -1");
        if (rs == null || !rs.next()) {
            try {
                ostmt.execute("INSERT INTO TROLE " + "(PKEY, LABEL, ACCESSKEY, EXTENDEDACCESSKEY, PROJECTTYPE) "
                        + "VALUES (-1, 'PrivateRole', 0, '111111111111', 0)");
                LOGGER.info("Inserted private role (PKEY = -1) into TROLE");
            } catch (Exception exc) {
                LOGGER.error("Problem inserting NULL object for TROLE: " + exc.getMessage());
                LOGGER.debug(STACKTRACE, exc);
            }
        }

        LOGGER.info("NULL objects are okay.");

        if (isFirstStartEver) {
            LOGGER.info("Filling some sample data...");
            try {

                URL populateURL = ApplicationBean.getInstance().getServletContext().getResource(populateSql);
                if (populateURL == null) {
                    ClassLoader cl = InitDatabase.class.getClassLoader();
                    populateURL = cl.getResource(populateSql);
                }
                InputStream in = populateURL.openStream();
                java.util.Scanner s = new java.util.Scanner(in, "UTF-8");
                s.useDelimiter(";");
                String st = null;
                StringBuffer stb = new StringBuffer();
                int line = 0;

                ApplicationStarter.getInstance().actualizePercentComplete(
                        ApplicationStarter.getInstance().INIT_DB_DATA_STEP,
                        ApplicationStarter.INIT_DB_DATA_TEXT);

                while (s.hasNext()) {
                    stb.append(s.nextLine().trim());
                    st = stb.toString();
                    ++line;
                    if (!st.isEmpty() && !st.startsWith("--") && !st.startsWith("/*")) {
                        if (st.endsWith(";")) {
                            stb = new StringBuffer(); // clear buffer
                            st = st.substring(0, st.length() - 1); // remove the semicolon
                            try {
                                ostmt.executeUpdate(st);
                            } catch (Exception exc) {
                                LOGGER.error("Problem inserting sample data: " + exc.getMessage());
                                LOGGER.error("Line " + line + ": " + st);
                            }
                        } else {
                            stb.append(" ");
                        }
                    } else {
                        stb = new StringBuffer();
                    }
                }
                s.close();
                in.close();

            } catch (Exception e) {
                LOGGER.error(ExceptionUtils.getStackTrace(e));
            }
            LOGGER.info("Sample data is okay.");

            ApplicationStarter.getInstance().actualizePercentComplete(
                    ApplicationStarter.getInstance().INIT_DB_DATA_STEP, ApplicationStarter.INIT_DB_DATA_TEXT);
        }
    } catch (Exception e) {
        LOGGER.error("Problem inserting null objects: " + e.getMessage());
        LOGGER.debug(STACKTRACE, e);
    } finally {
        if (coni != null) {
            try {
                coni.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
        if (cono != null) {
            try {
                cono.close();
            } catch (SQLException e) {
                LOGGER.info("Closing connection failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
}

From source file:com.flexive.core.search.SqlSearch.java

/**
 * Copy the query result to a briefcase//from   w  w w.java  2 s.  co  m
 *
 * @param con connection
 * @param ds  DataSelector
 * @param df DataFilter
 * @return briefcase id
 * @throws FxSqlSearchException on errors
 */
private long copyToBriefcase(Connection con, DataSelector ds, DataFilter df) throws FxSqlSearchException {
    FxSQLSearchParams.BriefcaseCreationData bcd = params.getBriefcaseCreationData();
    Statement stmt = null;
    try {
        // Create the briefcase
        long bid = briefcase.create(bcd.getName(), bcd.getDescription(), bcd.getAclId());
        stmt = con.createStatement();
        df.setVariable(stmt, "pos", "0");
        //            stmt.addBatch("SET @pos=0;");
        String sSql = "insert into " + DatabaseConst.TBL_BRIEFCASE_DATA + "(BRIEFCASE_ID,POS,ID,AMOUNT) "
                + "(select " + bid + "," + ds.getCounterStatement("pos") + ",data.id,1 from "
                + "(SELECT DISTINCT data2.id FROM " + getCacheTable() + " data2 WHERE data2.search_id="
                + getSearchId() + ") data)";
        //            stmt.addBatch(sSql);
        stmt.execute(sSql);
        return bid;
    } catch (Throwable t) {
        throw new FxSqlSearchException(LOG, t, "ex.sqlSearch.err.failedToBuildBriefcase", bcd.getName());
    } finally {
        Database.closeObjects(SqlSearch.class, null, stmt);
    }
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testSelectForUpdateLock() throws SQLException, InterruptedException {
    Statement stat = conn.createStatement();
    conn.setAutoCommit(false);//from  ww  w  .  j  a v  a2s .  c o m
    final Statement stat1 = conn.createStatement();
    final Statement stat2 = conn.createStatement();

    stat.execute("INSERT INTO test (column1,column2,column3) VALUES (1, 30001, 'testSelectForUpdateLock')");

    ResultSet rs = stat1.executeQuery("SELECT * FROM test WHERE column1=1 and column2=30001 for update");
    assertTrue(rs.next());
    assertTrue(rs.getString("column3").equals("testSelectForUpdateLock"));

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                stat2.executeUpdate(
                        "UPDATE test SET column3='testSelectForUpdateLock00' WHERE column1=1 and column2=30001");
                assertTrue(false);
                return;
            } catch (Exception e) {
                assertTrue(e.getMessage().contains("Timed out on getting lock for"));
                return;
            }
        }
    });
    thread.start();

    //Thread.currentThread().sleep(3000);

    stat1.executeUpdate("UPDATE test SET column3='testSelectForUpdateLock2' WHERE column1=1 and column2=30001");

    rs = stat1.executeQuery("SELECT * FROM test WHERE column1=1 and column2=30001");
    assertTrue(rs.next());
    assertTrue(rs.getString("column3").equals("testSelectForUpdateLock2"));

    stat2.executeUpdate(
            "UPDATE test SET column3='testSelectForUpdateLock00' WHERE column1=1 and column2=30001");

    rs = stat2.executeQuery("SELECT * FROM test WHERE column1=1 and column2=30001");
    assertTrue(rs.next());
    assertTrue(rs.getString("column3").equals("testSelectForUpdateLock00"));

}

From source file:edu.duke.cabig.c3pr.webservice.integration.StudyUtilityWebServiceTest.java

/**
 * Inserting data into registry_statuses via DbUnit was problematic; hence
 * this method with raw SQL./*from   ww  w  . j  a  v a2 s .co m*/
 * 
 * @throws SQLException
 * @throws Exception
 */
private void finishDatabaseSetup() throws SQLException, Exception {
    Connection conn = getConnection().getConnection();
    Statement st = conn.createStatement();
    boolean containsActive = st
            .executeQuery("SELECT id FROM registry_statuses WHERE code='" + STATUS_ACTIVE + "'").next();
    boolean containsInactive = st
            .executeQuery("SELECT id FROM registry_statuses WHERE code='" + STATUS_INACTIVE + "'").next();
    if (!containsActive) {
        st.execute(
                "INSERT INTO registry_statuses(id, version, grid_id, code, description, retired_indicator) VALUES ("
                        + STATUS_ACTIVE_ID + ",0,'" + System.currentTimeMillis() + "','" + STATUS_ACTIVE + "','"
                        + STATUS_ACTIVE + "','false')");
        st.execute(
                "insert into reasons(id,version,code,description,dtype,primary_indicator,registry_st_id,retired_indicator) VALUES ("
                        + STATUS_ACTIVE_ID + ",0,'" + TEST_PRIMARY_REASON_CODE + "','"
                        + TEST_PRIMARY_REASON_DESCR + "','" + REGISTRY_STATUS + "','" + 1 + "','"
                        + STATUS_ACTIVE_ID + "','false')");
    }
    if (!containsInactive) {
        st.execute(
                "INSERT INTO registry_statuses(id, version, grid_id, code, description, retired_indicator) VALUES ("
                        + STATUS_INACTIVE_ID + ",0,'" + System.currentTimeMillis() + "','" + STATUS_INACTIVE
                        + "','" + STATUS_INACTIVE + "','false')");
        st.execute(
                "insert into reasons(id,version,code,description,dtype,primary_indicator,registry_st_id,retired_indicator) VALUES ("
                        + STATUS_INACTIVE_ID + ",0,'" + TEST_PRIMARY_REASON_CODE + "','"
                        + TEST_PRIMARY_REASON_DESCR + "','" + REGISTRY_STATUS + "','" + 1 + "','"
                        + STATUS_INACTIVE_ID + "','false')");
    }
    st.close();
}

From source file:jp.co.tis.gsp.tools.dba.dialect.Dialect.java

protected void grantSchemaObjToUser(Connection conn, String grantListSql, String schema, String user,
        OBJECT_TYPE objType) throws SQLException {
    Statement stmt = null;
    ResultSet rs = null;//  w w  w  . j a va 2 s  .  c  om

    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(grantListSql);
        String grantSql = "";

        while (rs.next()) {
            switch (objType) {
            case TABLE: // 
                grantSql = "GRANT ALL ON " + schema + "." + rs.getString(1) + " TO " + user;
                break;
            case VIEW: // 
                grantSql = "GRANT ALL ON " + schema + "." + rs.getString(1) + " TO " + user;
                break;
            case SEQUENCE: // 
                grantSql = "GRANT ALL ON " + schema + "." + rs.getString(1) + " TO " + user;
                break;
            default:
                break;
            }

            stmt = conn.createStatement();
            System.err.println(grantSql);
            stmt.execute(grantSql);
        }
    } finally {
        StatementUtil.close(stmt);
    }
}

From source file:com.jspxcms.core.setup.SetupServlet.java

private void createDatabaseTable(String host, String port, String name, String user, String password,
        String adminUsername, String adminPassword, String version, String webPort, String contextPath)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException,
        IOException {//from   w w w  .  j a  v  a2 s.co m
    Connection connection = getConnection(host, port, name, user, password);
    Statement statement = connection.createStatement();
    String tablePath = getServletContext().getRealPath("/setup/database/1_table_sql.txt");
    excuteSQL(statement, new File(tablePath));
    String dataPath = getServletContext().getRealPath("/setup/database/2_data_sql.txt");
    excuteSQL(statement, new File(dataPath));
    String referencePath = getServletContext().getRealPath("/setup/database/3_reference_sql.txt");
    excuteSQL(statement, new File(referencePath));

    // ???
    byte[] saltBytes = Digests.generateSalt(8);
    String salt = Encodes.encodeHex(saltBytes);
    String sql;
    if (StringUtils.isNotBlank(adminPassword)) {
        SHA1CredentialsDigest digest = new SHA1CredentialsDigest();
        String encPass = digest.digest(adminPassword, saltBytes);
        sql = "update cms_user set f_username='" + adminUsername + "',f_password='" + encPass + "', f_salt='"
                + salt + "' where f_user_id=1";
        System.out.println(sql);
        statement.execute(sql);
    } else {
        sql = "update cms_user set f_username='" + adminUsername + "',f_password=null, f_salt='" + salt
                + "' where f_user_id=1";
        System.out.println(sql);
        statement.execute(sql);
    }
    // ?
    sql = "update cms_global set f_version='" + version + "'";
    System.out.println(sql);
    statement.execute(sql);
    // ??
    if (StringUtils.isNotBlank(webPort)) {
        sql = "update cms_global set f_port='" + webPort + "'";
        System.out.println(sql);
        statement.execute(sql);
    } else {
        sql = "update cms_global set f_port=null";
        System.out.println(sql);
        statement.execute(sql);
    }
    if (StringUtils.isNotBlank(contextPath)) {
        sql = "update cms_global set f_context_path='" + contextPath + "'";
        System.out.println(sql);
        statement.execute(sql);
    } else {
        sql = "update cms_global set f_context_path=null";
        System.out.println(sql);
        statement.execute(sql);
    }
    statement.close();
    connection.close();
}

From source file:com.qrmedia.commons.test.dbunit.operation.MySqlKeycheckIgnoringOperation.java

@Override
public void execute(IDatabaseConnection connection, IDataSet dataSet)
        throws DatabaseUnitException, SQLException {
    Connection jdbcConnection = connection.getConnection();
    Statement statement = null;
    String dbProductName = jdbcConnection.getMetaData().getDatabaseProductName();
    boolean dbProviderIsMySql = ((dbProductName != null) && dbProductName.contains(MYSQL_PRODUCT_NAME));
    Integer initialParameterValue = null;

    // the SQL to get and set the key checking variable's value
    final String getParameterValueSql = "select " + MYSQL_KEYCHECK_PARAMETER_NAME;
    final String setParameterValueSql = "set " + MYSQL_KEYCHECK_PARAMETER_NAME + " = ";

    // if running on MySQL, backup the existing value of the parameter and switch off key checking
    if (dbProviderIsMySql) {
        ResultSet resultSet;/*ww w .  j a  va2s  .  c o m*/
        statement = jdbcConnection.createStatement();
        resultSet = statement.executeQuery(getParameterValueSql);

        // the select statment returns only one row of one column - the value of the parameter
        resultSet.next();
        initialParameterValue = Integer.valueOf(resultSet.getInt(1));

        if (LOG.isInfoEnabled()) {
            LOG.info("Disabling MySQL foreign key checking.");
        }

        // XXX: could perhaps use a prepared statement for this, as it will be called twice
        statement.execute(setParameterValueSql + "0");
    }

    // execute the actual operation
    decoratedOperation.execute(connection, dataSet);

    // restore the value of the key checking property, if running on MySQL, and clean up
    if (dbProviderIsMySql) {

        if (LOG.isInfoEnabled()) {
            LOG.info("Enabling MySQL foreign key checking.");
        }

        statement.execute(setParameterValueSql + initialParameterValue);
        statement.close();
    }

    // leave the connection open - DbUnit is responsible for handling it
}

From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java

public void run() {

    BufferedReader d = null;// www. j  a  v  a 2s. c om
    Connection conn = null;

    if (conn == null) {

        try {
            long execTime = 0;
            int pkStart = 0;
            int pkEnds = 0;
            int intDeleteInterval = 0;
            int intBlobInterval = 0;
            int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
            ThreadInfo thInfo;

            long threadTimeStart = System.currentTimeMillis();
            active = true;

            thInfo = new ThreadInfo();
            thInfo.setId(this.ID);
            thInfo.setType("insert");
            thInfo.setStatusActive(this.isActive());

            StressTool.setInfo(this.ID, thInfo);
            boolean lazy = false;
            int lazyInterval = 0;

            for (int repeat = 0; repeat <= repeatNumber; repeat++) {

                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");
                ResultSet rs = null;
                int ServerId = 0;
                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                {
                    SoftReference sf = new SoftReference(
                            stmt.executeQuery("show global variables like 'SERVER_ID'"));
                    rs = (ResultSet) sf.get();
                }
                rs.next();
                ServerId = rs.getInt(2);

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval = StressTool.getNumberFromRandom(10).intValue();
                //               intBlobInterval++;
                //IMPLEMENTING lazy

                Vector v = null;
                {
                    SoftReference sf = new SoftReference(this.getTablesValues(lazy, ServerId));
                    v = (Vector) sf.get();
                }
                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    stmt.execute("SET GLOBAL max_allowed_packet=10737418");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        //                      System.out.println("Blob insert value :" + intBlobInterval);
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            //                        intBlobInterval=0;

                        }
                    }

                    iLine = stmt.executeBatch();
                    stmt.clearBatch();
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (Exception sqle) {
                    conn.rollback();
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY1==" + insert1));
                        StressTool.getErrorLogHandler().appendToFile(("FAILED QUERY2==" + insert2));
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());

                    } else {
                        sqle.printStackTrace();
                        System.out.println("FAILED QUERY1==" + insert1);
                        System.out.println("FAILED QUERY2==" + insert2);
                        sqle.printStackTrace();
                        System.exit(1);
                    }
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    stmt.execute("COMMIT");
                    rs.close();
                    stmt.close();
                    rs = null;
                    stmt = null;

                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

                conn.close();
                conn = null;
            }

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);
            active = false;
            //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfo(this.ID, thInfo);
            return;

        } catch (Exception ex) {
            if (StressTool.getErrorLogHandler() != null) {
                StressTool.getErrorLogHandler().appendToFile(ex.toString() + "\n");
            } else
                ex.printStackTrace();

            try {
                conn.close();
                conn = null;
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                if (StressTool.getErrorLogHandler() != null) {
                    StressTool.getErrorLogHandler().appendToFile(e.toString() + "\n");
                    conn = null;
                } else
                    e.printStackTrace();
            }
        }

    }

}