Example usage for java.sql PreparedStatement getParameterMetaData

List of usage examples for java.sql PreparedStatement getParameterMetaData

Introduction

In this page you can find the example usage for java.sql PreparedStatement getParameterMetaData.

Prototype

ParameterMetaData getParameterMetaData() throws SQLException;

Source Link

Document

Retrieves the number, types and properties of this PreparedStatement object's parameters.

Usage

From source file:org.broad.igv.dev.db.SQLCodecSource.java

private CloseableTribbleIterator query(String chr, int start, int end) throws IOException {
    initQueryStatement();//  w  ww . ja va  2 s. c om
    PreparedStatement statement = queryStatement;
    Set<Integer> bins = calculateBins(start, end);
    //System.out.println("number of bins: " + bins.size());
    if (bins.size() < MAX_BINS && binnedQueryStatement != null) {
        statement = binnedQueryStatement;
    }

    try {
        statement.clearParameters();
        statement.setString(1, chr);
        statement.setInt(3, end);
        int[] cols = new int[] { 2, 4, 5 };
        for (Integer cc : cols) {
            statement.setInt(cc, start);
        }

        if (statement == binnedQueryStatement) {
            int qnum = 6;
            for (Integer bin : bins) {
                statement.setInt(qnum, bin);
                qnum++;
            }

            for (; qnum <= statement.getParameterMetaData().getParameterCount(); qnum++) {
                statement.setNull(qnum, Types.INTEGER);
            }
        }

    } catch (SQLException e) {
        log.error(e);
        throw new IOException(e);
    }

    return loadIterator(statement);
}

From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java

public synchronized List<WebSocketMessageDTO> getMessages(WebSocketMessageDTO criteria, List<Integer> opcodes,
        List<Integer> inScopeChannelIds, WebSocketMessagesPayloadFilter payloadFilter, int offset, int limit,
        int payloadPreviewLength) throws DatabaseException {
    try {//w w w. j  ava 2 s.c o  m
        String query = "SELECT m.message_id, m.channel_id, m.timestamp, m.opcode, m.payload_length, m.is_outgoing, "
                + "m.payload_utf8, m.payload_bytes, " + "f.fuzz_id, f.state, f.fuzz "
                + "FROM websocket_message AS m " + "LEFT OUTER JOIN websocket_message_fuzz f "
                + "ON m.message_id = f.message_id AND m.channel_id = f.channel_id " + "<where> "
                + "ORDER BY m.timestamp, m.channel_id, m.message_id " + "LIMIT ? " + "OFFSET ?";

        PreparedStatement stmt;
        try {
            stmt = buildMessageCriteriaStatement(query, criteria, opcodes, inScopeChannelIds);
        } catch (SQLException e) {
            if (getConnection().isClosed()) {
                return new ArrayList<>(0);
            }

            throw e;
        }

        try {
            int paramsCount = stmt.getParameterMetaData().getParameterCount();
            stmt.setInt(paramsCount - 1, limit);
            stmt.setInt(paramsCount, offset);

            stmt.execute();

            return checkPayloadFilter(payloadFilter,
                    buildMessageDTOs(stmt.getResultSet(), true, payloadPreviewLength));
        } finally {
            stmt.close();
        }
    } catch (SQLException e) {
        throw new DatabaseException(e);
    }
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.query.PhoenixTransactSQL.java

private static PreparedStatement setQueryParameters(PreparedStatement stmt, Condition condition)
        throws SQLException {
    int pos = 1;//from www.  j a v a  2 s.co m
    //For GET_LATEST_METRIC_SQL_SINGLE_HOST parameters should be set 2 times
    do {
        if (condition.getMetricNames() != null) {
            for (String metricName : condition.getMetricNames()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting pos: " + pos + ", value = " + metricName);
                }
                stmt.setString(pos++, metricName);
            }
        }
        if (condition.getHostnames() != null) {
            for (String hostname : condition.getHostnames()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting pos: " + pos + ", value: " + hostname);
                }
                stmt.setString(pos++, hostname);
            }
        }
        if (condition.getAppId() != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting pos: " + pos + ", value: " + condition.getAppId());
            }
            stmt.setString(pos++, condition.getAppId());
        }
        if (condition.getInstanceId() != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting pos: " + pos + ", value: " + condition.getInstanceId());
            }
            stmt.setString(pos++, condition.getInstanceId());
        }

        if (condition.getFetchSize() != null) {
            stmt.setFetchSize(condition.getFetchSize());
            pos++;
        }
    } while (pos < stmt.getParameterMetaData().getParameterCount());

    return stmt;
}

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

/**
 * When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread causes the object's <code>run</code> method to be called in
 * that separately executing thread./*w ww  .j a  va  2 s.co m*/
 *
 * @todo Implement this java.lang.Runnable method
 */
public void run() {

    Connection conn = createConnection();

    if (conn != null) {
        ThreadInfo thInfo;
        thInfo = new ThreadInfo();
        thInfo.setId(this.ID);
        thInfo.setType("select");
        active = true;
        thInfo.setStatusActive(this.isActive());
        StressTool.setInfoSelect(this.ID, thInfo);

        try {
            Statement stmt = null;
            ResultSet rs = null;
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            PreparedStatement pstmt;
            long execTime = 0;
            int repeat = 0;
            int sqlParameterNumbers = 0;

            long threadTimeStart = System.currentTimeMillis();

            if (this.sqlQuery != null && !this.sqlQuery.equals("")) {
                try {

                    pstmt = conn.prepareStatement(sqlQuery);
                    sqlParameterNumbers = pstmt.getParameterMetaData().getParameterCount();

                } catch (SQLException sqlex) {
                    sqlex.printStackTrace();
                    conn.close();
                    return;
                }
            } else {
                pstmt = null;
            }

            String[][] sqlParameterValues;

            if (this.sqlQuery == null || this.sqlQuery.equals("")) {
                pkRange = new PrimaryKeyRangeDefiner(repeatNumber);
                pkRange.setLastResetLoop(0);
                pkRange = setPkRange(conn, pkRange);

                //                              3351000110
                sqlParameterValues = null;
            } else {
                sqlParameterValues = new String[repeatNumber][sqlParameterNumbers];
                for (repeat = 0; repeat < repeatNumber; repeat++) {
                    for (int pvalue = 0; pvalue < sqlParameterNumbers; pvalue++) {
                        sqlParameterValues[repeat][pvalue] = "3"
                                + String.valueOf(StressTool.getNumberFromRandom(500000000).intValue());
                    }
                }

            }

            for (repeat = 0; repeat < repeatNumber; repeat++) {
                int pkStart = 0;
                int pkEnds = 0;
                int recordFound = 0;
                if (repeat > 0 && pkRange.getLooprefresh() < (repeat - pkRange.getLastResetLoop())) {
                    pkRange = setPkRange(conn, pkRange);
                    pkRange.setLastResetLoop(repeat);
                }

                if (pkRange.getKeyStart(repeat) > 0 && pkRange.getKeyEnd(repeat) > 0) {
                    pkStart = pkRange.getKeyStart(repeat);
                    pkEnds = pkRange.getKeyEnd(repeat);
                }

                if (pkStart > pkEnds) {
                    int dummy = pkStart;
                    pkStart = pkEnds;
                    pkEnds = dummy;
                }

                if (pkEnds == 0)
                    continue;

                String select = "";

                select = generateSelectString(pkStart, pkEnds, select);
                int[] iLine = null;

                try {

                    long timeStart = System.currentTimeMillis();

                    try {
                        if (this.sqlQuery != null && !this.sqlQuery.equals("")) {

                            if (this.getIBatchSelect() > 0) {
                                for (int pstmtbatch = 0; pstmtbatch < this.getIBatchSelect(); pstmtbatch++) {
                                    for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                        pstmt.setString(ii, sqlParameterValues[StressTool
                                                .getNumberFromRandom(repeatNumber).intValue()][ii - 1]);
                                        rs = pstmt.executeQuery();
                                        //                                             System.out.print(this.sqlQuery + " BATCH | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                    }
                                }
                            } else {
                                for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                    pstmt.setString(ii, sqlParameterValues[repeat][ii - 1]);
                                    //                                        System.out.print(this.sqlQuery + " | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                }
                                rs = pstmt.executeQuery();

                            }

                        } else {
                            rs = stmt.executeQuery(select);
                            rs.last();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        if (rs != null) {
                            rs.close();
                            rs = null;
                        }

                    }
                    long timeEnds = System.currentTimeMillis();
                    //                            recordFound = rs.getRow();

                    execTime = (timeEnds - timeStart);
                    thInfo.setExecutedLoops(repeat);

                } catch (SQLException sqle) {

                    sqle.printStackTrace();
                } finally {
                    if (rs != null) {
                        rs.close();
                        rs = null;
                    }

                    //                            intDeleteInterval++;
                    if (doLog)
                        System.out.println(
                                "Query Select TH = " + this.getID() + " Id = " + pkStart + " IdEnd = " + pkEnds
                                        + " Record found = " + recordFound + " Exec Time(ms) =" + execTime);
                    Thread.sleep(sleepFor);
                }

                if (sleepFor > 0 || this.getSleepSelect() > 0) {
                    if (this.getSleepSelect() > 0) {
                        Thread.sleep(getSleepSelect());
                    } else
                        Thread.sleep(sleepFor);
                }
            }
            //                System.out.println("Query Select/Delete TH = " + this.getID() + " COMPLETED! ");

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);

            active = false;
            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfoSelect(this.ID, thInfo);
            stmt = null;

            return;

        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

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

/**
 * When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread causes the object's <code>run</code> method to be called in
 * that separately executing thread./* www.j  a  v a 2s. c o m*/
 *
 * @todo Implement this java.lang.Runnable method
 */
public void run() {

    Connection conn = createConnection();

    if (conn != null) {
        ThreadInfo thInfo;
        thInfo = new ThreadInfo();
        thInfo.setId(this.ID);
        thInfo.setType("select");
        active = true;
        thInfo.setStatusActive(this.isActive());
        StressTool.setInfoSelect(this.ID, thInfo);

        try {
            Statement stmt = null;
            ResultSet rs = null;
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            PreparedStatement pstmt;
            long execTime = 0;
            int repeat = 0;
            int sqlParameterNumbers = 0;

            long threadTimeStart = System.currentTimeMillis();

            if (this.sqlQuery != null && !this.sqlQuery.equals("")) {
                try {

                    pstmt = conn.prepareStatement(sqlQuery);
                    sqlParameterNumbers = pstmt.getParameterMetaData().getParameterCount();

                } catch (SQLException sqlex) {
                    sqlex.printStackTrace();
                    conn.close();
                    return;
                }
            } else {
                pstmt = null;
            }

            String[][] sqlParameterValues;

            if (this.sqlQuery == null || this.sqlQuery.equals("")) {
                pkRange = new PrimaryKeyRangeDefiner(repeatNumber);
                pkRange.setLastResetLoop(0);
                pkRange = setPkRange(conn, pkRange);

                //                              3351000110
                sqlParameterValues = null;
            } else {
                sqlParameterValues = new String[repeatNumber][sqlParameterNumbers];
                for (repeat = 0; repeat < repeatNumber; repeat++) {
                    for (int pvalue = 0; pvalue < sqlParameterNumbers; pvalue++) {
                        sqlParameterValues[repeat][pvalue] = "3"
                                + String.valueOf(StressTool.getNumberFromRandom(500000000).intValue());
                    }
                }

            }

            for (repeat = 0; repeat < repeatNumber; repeat++) {
                int pkStart = 0;
                int pkEnds = 0;
                int recordFound = 0;
                if (repeat > 0 && pkRange.getLooprefresh() < (repeat - pkRange.getLastResetLoop())) {
                    pkRange = setPkRange(conn, pkRange);
                    pkRange.setLastResetLoop(repeat);
                }

                if (pkRange.getKeyStart(repeat) > 0 && pkRange.getKeyEnd(repeat) > 0) {
                    pkStart = pkRange.getKeyStart(repeat);
                    pkEnds = pkRange.getKeyEnd(repeat);
                }

                if (pkStart > pkEnds) {
                    int dummy = pkStart;
                    pkStart = pkEnds;
                    pkEnds = dummy;
                }

                if (pkEnds == 0)
                    continue;

                // TODO Select is an Object not a string need to modify it
                /*Object needs to have list of tables Main and secondary (join)
                 * Levels of above relation
                 * Join field definition
                 * Filter attribute value (name of filter attribute)
                 * Filter value (array if more then one)
                 * SQL resulting
                 * More some meta information 
                 * */
                String select = "";

                int[] iLine = null;

                try {

                    long timeStart = System.currentTimeMillis();

                    try {
                        if (this.sqlQuery != null && !this.sqlQuery.equals("")) {

                            if (this.getIBatchSelect() > 0) {
                                for (int pstmtbatch = 0; pstmtbatch < this.getIBatchSelect(); pstmtbatch++) {
                                    for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                        pstmt.setString(ii, sqlParameterValues[StressTool
                                                .getNumberFromRandom(repeatNumber).intValue()][ii - 1]);
                                        rs = pstmt.executeQuery();
                                        //                                             System.out.print(this.sqlQuery + " BATCH | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                    }
                                }
                            } else {
                                for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                    pstmt.setString(ii, sqlParameterValues[repeat][ii - 1]);
                                    //                                        System.out.print(this.sqlQuery + " | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                }
                                rs = pstmt.executeQuery();

                            }

                        } else {
                            select = generateSelectString(pkStart, pkEnds);
                            rs = stmt.executeQuery(select);
                            rs.last();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    } finally {
                        if (rs != null) {
                            rs.close();
                            rs = null;
                        }

                    }
                    long timeEnds = System.currentTimeMillis();
                    //                            recordFound = rs.getRow();

                    execTime = (timeEnds - timeStart);
                    thInfo.setExecutedLoops(repeat);

                } catch (SQLException sqle) {

                    sqle.printStackTrace();
                } finally {
                    if (rs != null) {
                        rs.close();
                        rs = null;
                    }

                    //                            intDeleteInterval++;
                    if (doLog)
                        System.out.println(
                                "Query Select TH = " + this.getID() + " Id = " + pkStart + " IdEnd = " + pkEnds
                                        + " Record found = " + recordFound + " Exec Time(ms) =" + execTime);
                    Thread.sleep(sleepFor);
                }

                if (sleepFor > 0 || this.getSleepSelect() > 0) {
                    if (this.getSleepSelect() > 0) {
                        Thread.sleep(getSleepSelect());
                    } else
                        Thread.sleep(sleepFor);
                }
            }
            //                System.out.println("Query Select/Delete TH = " + this.getID() + " COMPLETED! ");

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);

            active = false;
            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfoSelect(this.ID, thInfo);
            stmt = null;

            return;

        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

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

/**
 * When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread causes the object's <code>run</code> method to be called in
 * that separately executing thread./*  w  ww. j ava  2s  .  co  m*/
 *
 * @todo Implement this java.lang.Runnable method
 */
public void run() {

    Connection conn = createConnection();
    {
        SoftReference sf = new SoftReference(createConnection());
        conn = (Connection) sf.get();
    }

    if (conn != null) {
        ThreadInfo thInfo;
        thInfo = new ThreadInfo();
        thInfo.setId(this.ID);
        thInfo.setType("select");
        active = true;
        thInfo.setStatusActive(this.isActive());
        StressTool.setInfoSelect(this.ID, thInfo);

        try {
            Statement stmt = null;
            ResultSet rs = null;
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            PreparedStatement pstmt;
            long execTime = 0;
            int repeat = 0;
            int sqlParameterNumbers = 0;

            long threadTimeStart = System.currentTimeMillis();

            if (this.sqlQuery != null && !this.sqlQuery.equals("")) {
                try {

                    pstmt = conn.prepareStatement(sqlQuery);
                    sqlParameterNumbers = pstmt.getParameterMetaData().getParameterCount();

                } catch (SQLException sqlex) {
                    sqlex.printStackTrace();
                    conn.close();
                    return;
                }
            } else {
                pstmt = null;
            }

            String[][] sqlParameterValues;

            if (this.sqlQuery == null || this.sqlQuery.equals("")) {
                pkRange = new PrimaryKeyRangeDefiner(repeatNumber);
                pkRange.setLastResetLoop(0);
                pkRange = setPkRange(conn, pkRange);

                //                              3351000110
                sqlParameterValues = null;
            } else {
                sqlParameterValues = new String[repeatNumber][sqlParameterNumbers];
                for (repeat = 0; repeat < repeatNumber; repeat++) {
                    for (int pvalue = 0; pvalue < sqlParameterNumbers; pvalue++) {
                        sqlParameterValues[repeat][pvalue] = "3"
                                + String.valueOf(StressTool.getNumberFromRandom(500000000).intValue());
                    }
                }

            }

            for (repeat = 0; repeat < repeatNumber; repeat++) {
                int pkStart = 0;
                int pkEnds = 0;
                int recordFound = 0;
                if (repeat > 0 && pkRange.getLooprefresh() < (repeat - pkRange.getLastResetLoop())) {
                    pkRange = setPkRange(conn, pkRange);
                    pkRange.setLastResetLoop(repeat);
                }

                if (pkRange.getKeyStart(repeat) > 0 && pkRange.getKeyEnd(repeat) > 0) {
                    pkStart = pkRange.getKeyStart(repeat);
                    pkEnds = pkRange.getKeyEnd(repeat);
                }

                if (pkStart > pkEnds) {
                    int dummy = pkStart;
                    pkStart = pkEnds;
                    pkEnds = dummy;
                }

                if (pkEnds == 0)
                    continue;

                String select = "";
                {
                    SoftReference sf = new SoftReference(generateSelectString(pkStart, pkEnds, select));
                    select = (String) sf.get();
                }
                int[] iLine = null;

                try {

                    long timeStart = System.currentTimeMillis();

                    try {
                        if (this.sqlQuery != null && !this.sqlQuery.equals("")) {

                            if (this.getIBatchSelect() > 0) {
                                for (int pstmtbatch = 0; pstmtbatch < this.getIBatchSelect(); pstmtbatch++) {
                                    for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                        pstmt.setString(ii, sqlParameterValues[StressTool
                                                .getNumberFromRandom(repeatNumber).intValue()][ii - 1]);
                                        {
                                            SoftReference sf = new SoftReference(pstmt.executeQuery());
                                            rs = (ResultSet) sf.get();
                                        }

                                        //                                             System.out.print(this.sqlQuery + " BATCH | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                    }
                                }
                            } else {
                                for (int ii = 1; ii <= sqlParameterNumbers; ii++) {
                                    pstmt.setString(ii, sqlParameterValues[repeat][ii - 1]);
                                    //                                        System.out.print(this.sqlQuery + " | " + ii +" | " + sqlParameterValues[repeat][ii - 1] + "\n") ;
                                }
                                rs = pstmt.executeQuery();

                            }

                        } else {
                            rs = stmt.executeQuery(select);
                            rs.last();
                        }
                    } catch (Exception ex) {
                        if (StressTool.getErrorLogHandler() != null) {
                            StressTool.getErrorLogHandler().appendToFile(ex.toString());
                        } else
                            ex.printStackTrace();
                    } finally {
                        if (rs != null) {
                            rs.close();
                            rs = null;
                        }

                    }
                    long timeEnds = System.currentTimeMillis();
                    //                            recordFound = rs.getRow();

                    execTime = (timeEnds - timeStart);
                    thInfo.setExecutedLoops(repeat);

                } catch (SQLException sqle) {
                    if (StressTool.getErrorLogHandler() != null) {
                        StressTool.getErrorLogHandler().appendToFile(sqle.toString());
                    } else
                        sqle.printStackTrace();
                } finally {
                    if (rs != null) {
                        rs.close();
                        rs = null;
                    }

                    //                            intDeleteInterval++;
                    if (doLog)
                        System.out.println(
                                "Query Select TH = " + this.getID() + " Id = " + pkStart + " IdEnd = " + pkEnds
                                        + " Record found = " + recordFound + " Exec Time(ms) =" + execTime);

                }

                if (sleepFor > 0 || this.getSleepSelect() > 0) {
                    if (this.getSleepSelect() > 0) {
                        Thread.sleep(getSleepSelect());
                    } else
                        Thread.sleep(sleepFor);
                }
            }
            //                System.out.println("Query Select/Delete TH = " + this.getID() + " COMPLETED! ");

            long threadTimeEnd = System.currentTimeMillis();
            this.executionTime = (threadTimeEnd - threadTimeStart);
            //                this.setExecutionTime(executionTime);

            active = false;
            thInfo.setExecutionTime(executionTime);
            thInfo.setStatusActive(false);
            StressTool.setInfoSelect(this.ID, thInfo);
            stmt = null;

            return;

        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

From source file:org.batoo.jpa.core.impl.criteria.QueryImpl.java

/**
 * Fills the statement with the parameters supplied.
 * //from  w  w  w.j  a va 2  s .c o  m
 * @param statement
 *            the statement
 * @param parameters
 *            the parameters
 * @param repeat
 *            the parameter repeat map
 * @throws SQLException
 *             thrown in case of an underlying SQL Exception
 * 
 * @since 2.0.0
 */
private void fillStatement(PreparedStatement statement, Object[] parameters, Map<Integer, Integer> repeat)
        throws SQLException {
    // the following code has been adopted from Apache Commons DBUtils.

    // no paramaters nothing to do
    if ((parameters == null) || (parameters.length == 0)) {
        return;
    }

    final ParameterMetaData pmd = this.pmdBroken ? null : statement.getParameterMetaData();

    if (this.pmdBroken) {
        int total = parameters.length - repeat.size();

        if (repeat.size() > 0) {
            for (final Integer repeatSize : repeat.values()) {
                if (repeatSize != null) {
                    total += repeatSize;
                }
            }
        }

        ((PreparedStatementProxy) statement).setParamCount(total);
    }

    int index = 1;
    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i] != null) {
            if (repeat.containsKey(i)) {
                final Object paramValue = parameters[i];

                if (paramValue instanceof Collection) {
                    final Collection<?> collection = (Collection<?>) paramValue;
                    for (final Object subParamValue : collection) {
                        statement.setObject(index++, subParamValue);
                    }
                } else {
                    final Object[] array = (Object[]) paramValue;
                    for (final Object subParamValue : array) {
                        statement.setObject(index++, subParamValue);
                    }
                }
            } else {
                statement.setObject(index++, parameters[i]);
            }
        } else {
            // VARCHAR works with many drivers regardless
            // of the actual column type. Oddly, NULL and
            // OTHER don't work with Oracle's drivers.
            int sqlType = Types.VARCHAR;
            if (!this.pmdBroken) {
                try {
                    sqlType = pmd.getParameterType(index + 1);
                } catch (final SQLException e) {
                    this.pmdBroken = true;
                }
            }

            statement.setNull(index++, sqlType);
        }
    }
}

From source file:com.gs.obevo.db.impl.core.jdbc.JdbcHelper.java

private int updateInternal(Connection conn, int retryCount, String sql, Object... args) {
    this.jdbcHandler.preUpdate(conn, this);

    Statement statement = null;/*from  w  ww.  j ava2 s .  c o m*/
    PreparedStatement ps = null;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing update on connection {}: {} with args: {}", displayConnection(conn), sql,
                    args);
        }
        if (args.length == 0) {
            // For args length == 0, we use regular Statements and not PreparedStatements
            // This is because of http://www.selikoff.net/2008/08/04/question-mark-%E2%80%98%E2%80%99-characters-as-text-in-jdbc/
            // In short - question marks are naively interpreted by PreparedStatements as parameters, even if in
            // strings or comments
            // This can affect legacy DDL files that may have such comments sprinkled in. So we go w/ Statements,
            // which is what spring-jdbc did (this product had used spring-jdbc in an early incarnation, which was
            // when we discovered this issue)
            statement = conn.createStatement();
            return statement.executeUpdate(sql);
        } else {
            ps = conn.prepareStatement(sql);
            for (int j = 0; j < args.length; j++) {
                if (!parameterTypeEnabled || args[j] != null) {
                    ps.setObject(j + 1, args[j]);
                } else {
                    ps.setNull(j + 1, ps.getParameterMetaData().getParameterType(j + 1));
                }
            }

            return ps.executeUpdate();
        }
    } catch (SQLException e) {
        DataAccessException dataAccessException = new DataAccessException(e);
        boolean retry = this.jdbcHandler.handleException(this, conn, retryCount, dataAccessException);
        if (retry) {
            return this.updateInternal(conn, retryCount + 1, sql, args);
        } else {
            throw dataAccessException;
        }
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(ps);
    }
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

/**
 * Execute an update//from ww  w  .j a v  a 2s .  c om
 * 
 * @param statementScope
 *            - the request scope
 * @param conn
 *            - the database connection
 * @param sql
 *            - the sql statement to execute
 * @param parameters
 *            - the parameters for the sql statement
 * @return - the number of records changed
 * @throws SQLException
 *             - if the update fails
 */
public int executeUpdate(StatementScope statementScope, Connection conn, String sql, Object[] parameters)
        throws SQLException {
    ErrorContext errorContext = statementScope.getErrorContext();
    errorContext.setActivity("executing update");
    errorContext.setObjectId(sql);
    PreparedStatement ps = null;
    setupResultObjectFactory(statementScope);
    int rows = 0;
    try {
        errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
        ps = prepareStatement(statementScope.getSession(), conn, sql);
        setStatementTimeout(statementScope.getStatement(), ps);
        errorContext.setMoreInfo("Check the parameters (set parameters failed).");
        statementScope.getParameterMap().setParameters(statementScope, ps, parameters);
        errorContext.setMoreInfo("Check the statement (update failed).");

        // ========================== print
        try {
            if (log.isInfoEnabled()) {
                int count = ps.getParameterMetaData().getParameterCount();
                for (int i = 0; i < count; i++) {
                    sql = sql.replaceFirst("\\?",
                            parameters[i].getClass().getName().equals("java.lang.String")
                                    ? "'" + parameters[i].toString() + "'"
                                    : parameters[i].toString());
                }
                String[] unPrintSql = { "update dw_websql_sqlcommand a set a.status = 1" };
                printSql(sql, unPrintSql);
            }
        } catch (Throwable t) {

        }
        // =========================== print

        ps.execute();
        rows = ps.getUpdateCount();
    } finally {
        closeStatement(statementScope.getSession(), ps);
    }
    return rows;
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

/**
 * Long form of the method to execute a query
 * //from  w  w w . j  av  a  2s .c om
 * @param statementScope
 *            - the request scope
 * @param conn
 *            - the database connection
 * @param sql
 *            - the SQL statement to execute
 * @param parameters
 *            - the parameters for the statement
 * @param skipResults
 *            - the number of results to skip
 * @param maxResults
 *            - the maximum number of results to return
 * @param callback
 *            - the row handler for the query
 * @throws SQLException
 *             - if the query fails
 */
public void executeQuery(StatementScope statementScope, Connection conn, String sql, Object[] parameters,
        int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {
    ErrorContext errorContext = statementScope.getErrorContext();
    errorContext.setActivity("executing query");
    errorContext.setObjectId(sql);
    PreparedStatement ps = null;
    ResultSet rs = null;
    setupResultObjectFactory(statementScope);
    try {
        errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");
        Integer rsType = statementScope.getStatement().getResultSetType();
        if (rsType != null) {
            ps = prepareStatement(statementScope.getSession(), conn, sql, rsType);
        } else {
            ps = prepareStatement(statementScope.getSession(), conn, sql);
        }
        setStatementTimeout(statementScope.getStatement(), ps);
        Integer fetchSize = statementScope.getStatement().getFetchSize();
        if (fetchSize != null) {
            ps.setFetchSize(fetchSize.intValue());
        }
        errorContext.setMoreInfo("Check the parameters (set parameters failed).");
        statementScope.getParameterMap().setParameters(statementScope, ps, parameters);
        errorContext.setMoreInfo("Check the statement (query failed).");

        // ========================== print
        if (log.isInfoEnabled()) {
            int count = ps.getParameterMetaData().getParameterCount();
            for (int i = 0; i < count; i++) {
                sql = sql.replaceFirst("\\?",
                        parameters[i].getClass().getName().equals("java.lang.String")
                                ? "'" + parameters[i].toString() + "'"
                                : parameters[i].toString());
            }
            String[] unPrintSql = { "select * from dw_websql_sqlcommand a where a.ds_id ",
                    "select count(1) from dw_websql_sqlcommand ", "select sql_id , user_code , submit_sql ,",
                    "select * from dw_websql_sqlcommand" };

            printSql(sql, unPrintSql);
        }
        // =========================== print

        ps.execute();
        errorContext.setMoreInfo("Check the results (failed to retrieve results).");

        // Begin ResultSet Handling
        rs = handleMultipleResults(ps, statementScope, skipResults, maxResults, callback);
        // End ResultSet Handling
    } finally {
        try {
            closeResultSet(rs);
        } finally {
            closeStatement(statementScope.getSession(), ps);
        }
    }

}