Example usage for java.sql PreparedStatement setClob

List of usage examples for java.sql PreparedStatement setClob

Introduction

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

Prototype

void setClob(int parameterIndex, Reader reader) throws SQLException;

Source Link

Document

Sets the designated parameter to a Reader object.

Usage

From source file:org.waarp.common.database.data.AbstractDbData.java

/**
 * Set Value into PreparedStatement/*from  w w  w .  ja  v a 2s.c o  m*/
 * 
 * @param ps
 * @param value
 * @param rank
 *            >= 1
 * @throws WaarpDatabaseSqlException
 */
static public void setTrueValue(PreparedStatement ps, DbValue value, int rank)
        throws WaarpDatabaseSqlException {
    try {
        switch (value.type) {
        case Types.VARCHAR:
            if (value.value == null) {
                ps.setNull(rank, Types.VARCHAR);
                break;
            }
            ps.setString(rank, (String) value.value);
            break;
        case Types.LONGVARCHAR:
            if (value.value == null) {
                ps.setNull(rank, Types.LONGVARCHAR);
                break;
            }
            ps.setString(rank, (String) value.value);
            break;
        case Types.BIT:
            if (value.value == null) {
                ps.setNull(rank, Types.BIT);
                break;
            }
            ps.setBoolean(rank, (Boolean) value.value);
            break;
        case Types.TINYINT:
            if (value.value == null) {
                ps.setNull(rank, Types.TINYINT);
                break;
            }
            ps.setByte(rank, (Byte) value.value);
            break;
        case Types.SMALLINT:
            if (value.value == null) {
                ps.setNull(rank, Types.SMALLINT);
                break;
            }
            ps.setShort(rank, (Short) value.value);
            break;
        case Types.INTEGER:
            if (value.value == null) {
                ps.setNull(rank, Types.INTEGER);
                break;
            }
            ps.setInt(rank, (Integer) value.value);
            break;
        case Types.BIGINT:
            if (value.value == null) {
                ps.setNull(rank, Types.BIGINT);
                break;
            }
            ps.setLong(rank, (Long) value.value);
            break;
        case Types.REAL:
            if (value.value == null) {
                ps.setNull(rank, Types.REAL);
                break;
            }
            ps.setFloat(rank, (Float) value.value);
            break;
        case Types.DOUBLE:
            if (value.value == null) {
                ps.setNull(rank, Types.DOUBLE);
                break;
            }
            ps.setDouble(rank, (Double) value.value);
            break;
        case Types.VARBINARY:
            if (value.value == null) {
                ps.setNull(rank, Types.VARBINARY);
                break;
            }
            ps.setBytes(rank, (byte[]) value.value);
            break;
        case Types.DATE:
            if (value.value == null) {
                ps.setNull(rank, Types.DATE);
                break;
            }
            ps.setDate(rank, (Date) value.value);
            break;
        case Types.TIMESTAMP:
            if (value.value == null) {
                ps.setNull(rank, Types.TIMESTAMP);
                break;
            }
            ps.setTimestamp(rank, (Timestamp) value.value);
            break;
        case Types.CLOB:
            if (value.value == null) {
                ps.setNull(rank, Types.CLOB);
                break;
            }
            ps.setClob(rank, (Reader) value.value);
            break;
        case Types.BLOB:
            if (value.value == null) {
                ps.setNull(rank, Types.BLOB);
                break;
            }
            ps.setBlob(rank, (InputStream) value.value);
            break;
        default:
            throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " at " + rank);
        }
    } catch (ClassCastException e) {
        throw new WaarpDatabaseSqlException("Setting values casting error: " + value.type + " at " + rank, e);
    } catch (SQLException e) {
        DbSession.error(e);
        throw new WaarpDatabaseSqlException("Setting values in error: " + value.type + " at " + rank, e);
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private boolean setStateMergeDB(Map<String, String> nameStates, int epoch, RCStates state,
        Set<NodeIDType> newActives) {
    String updateCmd = "update " + getRCRecordTable() + " set " + Columns.RC_GROUP_NAME.toString() + "=?, "
            + Columns.STRINGIFIED_RECORD.toString() + "=? where " + Columns.SERVICE_NAME.toString() + "=?";

    PreparedStatement updateRC = null;
    Connection conn = null;/* ww w .  ja  va 2  s.  c o m*/
    boolean updatedAll = true;
    try {
        if (conn == null) {
            conn = this.getDefaultConn();
            conn.setAutoCommit(false);
            updateRC = conn.prepareStatement(updateCmd);
        }
        assert (nameStates != null && !nameStates.isEmpty());
        String rcGroupName = this.getRCGroupName(nameStates.keySet().iterator().next());
        int i = 0;
        long t1 = System.currentTimeMillis();
        for (String name : nameStates.keySet()) {
            ReconfigurationRecord<NodeIDType> record = new ReconfigurationRecord<NodeIDType>(name, 0,
                    newActives);
            record.setState(name, 0, state/* RCStates.READY_READY */).setActivesToNewActives();
            ;
            updateRC.setString(1, rcGroupName);
            if (RC_RECORD_CLOB_OPTION)
                updateRC.setClob(2, new StringReader(record.toString()));
            else
                updateRC.setString(2, record.toString());
            updateRC.setString(3, name);
            updateRC.addBatch();
            i++;
            if ((i + 1) % MAX_DB_BATCH_SIZE == 0 || (i + 1) == nameStates.size()) {
                int[] executed = updateRC.executeBatch();
                conn.commit();
                updateRC.clearBatch();
                for (int j : executed)
                    updatedAll = updatedAll && (j > 0);
                if (updatedAll)
                    log.log(Level.FINE, "{0} successfully logged the last {1} messages in {2} ms",
                            new Object[] { this, (i + 1), (System.currentTimeMillis() - t1) });
                t1 = System.currentTimeMillis();
            }
        }
    } catch (SQLException sqle) {
        log.severe("SQLException while inserting batched RC records using " + updateCmd);
        sqle.printStackTrace();
    } finally {
        cleanup(updateRC);
        cleanup(conn);
    }
    return updatedAll;
}

From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java

/**
 * Runs the udpateChangeset prepared statement.
  * <code>/*  w  ww .java  2  s . com*/
 *        UPDATE {0} SET ADDGRAPH=?,REMOVEGRAPH=? ,METAADDGRAPH=?,METAREMOVEGRAPH=? WHERE ID=?    
 * </code>
 *
 *@param stmtProvider
 *         factory and cache of PreparedStatments
 *@param connection
 *          connection to underlying database
 *
 *@param addGraph template parameter
 *@param removeGraph template parameter
 *@param addMetaGraph template parameter
 *@param removeMetaGraph template parameter
 *@param id template parameter
 *
 *@param transactionTableName template parameter
 *@return  int
 *@throws  org.openanzo.jdbc.utils.RdbException
 */
public static int udpateChangeset(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider,
        final java.sql.Connection connection, java.sql.Clob addGraph, java.sql.Clob removeGraph,
        java.sql.Clob addMetaGraph, java.sql.Clob removeMetaGraph, long id, String transactionTableName)
        throws org.openanzo.jdbc.utils.RdbException {
    java.sql.PreparedStatement ps = null;
    //long startTimer=System.currentTimeMillis();
    try {
        ps = stmtProvider.getPreparedSQLStatement(udpateChangeset, new String[] { transactionTableName },
                connection);
        int argc = 1;
        if (addGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, addGraph);
        }
        if (removeGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, removeGraph);
        }
        if (addMetaGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, addMetaGraph);
        }
        if (removeMetaGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, removeMetaGraph);
        }
        ps.setLong(argc++, id);
        int counter = 0;
        try {
            counter = ps.executeUpdate();
        } catch (java.sql.SQLException sqle) {
            if (sqle.getErrorCode() == 1205) {
                int retries = 0;
                while (retries < 5) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ie) {
                        throw sqle;
                    }
                    try {
                        counter = ps.executeUpdate();
                        break;
                    } catch (java.sql.SQLException sqleInner) {
                        if (sqleInner.getErrorCode() == 1205) {
                            retries++;
                        } else {
                            throw sqleInner;
                        }
                    }
                }
                if (retries >= 5) {
                    throw sqle;
                }
            } else {
                throw sqle;
            }
        }
        return counter;

    } catch (java.sql.SQLException e) {
        throw new org.openanzo.jdbc.utils.RdbException(
                org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "udpateChangeset",
                stmtProvider.getSqlString(udpateChangeset),
                "" + "addGraph=" + ((addGraph != null) ? addGraph.toString() : "null") + "," + "removeGraph="
                        + ((removeGraph != null) ? removeGraph.toString() : "null") + "," + "addMetaGraph="
                        + ((addMetaGraph != null) ? addMetaGraph.toString() : "null") + "," + "removeMetaGraph="
                        + ((removeMetaGraph != null) ? removeMetaGraph.toString() : "null") + "," + "id="
                        + (id),
                "" + "transactionTableName="
                        + ((transactionTableName != null) ? transactionTableName.toString() : "null"));
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (java.sql.SQLException sqle) {
                if (log.isDebugEnabled())
                    log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement",
                            sqle);
            }
        }
        //long endtimer=(System.currentTimeMillis()-startTimer);
        //if(endtimer>CUTOFF)System.out.println("[udpateChangeset]"+endtimer);
    }
}

From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java

/**
 * Runs the insertChangeset prepared statement.
  * <code>//from   www.ja  va  2 s .  c  o m
 *        INSERT INTO {0} (commandId, addGraph,removeGraph,metaddgraph,metaremovegraph,namedGraphUri) VALUES (?, ?, ?, ?,?,?)    
 * </code>
 *
 *@param stmtProvider
 *         factory and cache of PreparedStatments
 *@param connection
 *          connection to underlying database
 *
 *@param commandId template parameter
 *@param addGraph template parameter
 *@param removeGraph template parameter
 *@param addMetaGraph template parameter
 *@param removeMetaGraph template parameter
 *@param uri template parameter
 *
 *@param transactionTableName template parameter
 *@return  int
 *@throws  org.openanzo.jdbc.utils.RdbException
 */
public static int insertChangeset(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider,
        final java.sql.Connection connection, long commandId, java.sql.Clob addGraph, java.sql.Clob removeGraph,
        java.sql.Clob addMetaGraph, java.sql.Clob removeMetaGraph, String uri, String transactionTableName)
        throws org.openanzo.jdbc.utils.RdbException {
    java.sql.PreparedStatement ps = null;
    //long startTimer=System.currentTimeMillis();
    try {
        ps = stmtProvider.getPreparedSQLStatement(insertChangeset, new String[] { transactionTableName },
                connection);
        int argc = 1;
        ps.setLong(argc++, commandId);
        if (addGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, addGraph);
        }
        if (removeGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, removeGraph);
        }
        if (addMetaGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, addMetaGraph);
        }
        if (removeMetaGraph == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, removeMetaGraph);
        }
        if (uri == null) {
            ps.setNull(argc++, java.sql.Types.VARCHAR);
        } else {
            ps.setString(argc++, uri);
        }
        int counter = 0;
        try {
            counter = ps.executeUpdate();
        } catch (java.sql.SQLException sqle) {
            if (sqle.getErrorCode() == 1205) {
                int retries = 0;
                while (retries < 5) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ie) {
                        throw sqle;
                    }
                    try {
                        counter = ps.executeUpdate();
                        break;
                    } catch (java.sql.SQLException sqleInner) {
                        if (sqleInner.getErrorCode() == 1205) {
                            retries++;
                        } else {
                            throw sqleInner;
                        }
                    }
                }
                if (retries >= 5) {
                    throw sqle;
                }
            } else {
                throw sqle;
            }
        }
        return counter;

    } catch (java.sql.SQLException e) {
        throw new org.openanzo.jdbc.utils.RdbException(
                org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "insertChangeset",
                stmtProvider.getSqlString(insertChangeset),
                "" + "commandId=" + (commandId) + "," + "addGraph="
                        + ((addGraph != null) ? addGraph.toString() : "null") + "," + "removeGraph="
                        + ((removeGraph != null) ? removeGraph.toString() : "null") + "," + "addMetaGraph="
                        + ((addMetaGraph != null) ? addMetaGraph.toString() : "null") + "," + "removeMetaGraph="
                        + ((removeMetaGraph != null) ? removeMetaGraph.toString() : "null") + "," + "uri="
                        + ((uri != null) ? uri.toString() : "null"),
                "" + "transactionTableName="
                        + ((transactionTableName != null) ? transactionTableName.toString() : "null"));
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (java.sql.SQLException sqle) {
                if (log.isDebugEnabled())
                    log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement",
                            sqle);
            }
        }
        //long endtimer=(System.currentTimeMillis()-startTimer);
        //if(endtimer>CUTOFF)System.out.println("[insertChangeset]"+endtimer);
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private Set<String> putReconfigurationRecordDB(Map<String, ReconfigurationRecord<NodeIDType>> toCommit) {
    String updateCmd = "update " + getRCRecordTable() + " set " + Columns.RC_GROUP_NAME.toString() + "=?, "
            + Columns.STRINGIFIED_RECORD.toString() + "=? where " + Columns.SERVICE_NAME.toString() + "=?";
    String cmd = updateCmd;//from  www.  j a  v a 2s  .  c  o m

    PreparedStatement pstmt = null;
    Connection conn = null;
    Set<String> committed = new HashSet<String>();
    String[] keys = toCommit.keySet().toArray(new String[0]);
    try {
        ArrayList<String> batch = new ArrayList<String>();
        for (int i = 0; i < keys.length; i++) {
            String name = keys[i];
            if (conn == null) {
                conn = this.getDefaultConn();
                conn.setAutoCommit(false);
                pstmt = conn.prepareStatement(updateCmd);
            }
            // removal
            if (toCommit.get(name) == null) {
                this.deleteReconfigurationRecordDB(name);
                log.log(Level.INFO, "{0} deleted RC record {1}", new Object[] { this, name });
                committed.add(name);
                continue;
            }
            // else update/insert
            String rcGroupName = toCommit.get(name).getRCGroupName();
            if (rcGroupName == null)
                rcGroupName = this.getRCGroupName(name);
            pstmt.setString(1, rcGroupName);
            if (RC_RECORD_CLOB_OPTION)
                pstmt.setClob(2, new StringReader((toCommit.get(name)).toString()));
            else
                pstmt.setString(2, (toCommit.get(name)).toString());
            pstmt.setString(3, name);
            pstmt.addBatch();
            batch.add(name);

            int[] executed = new int[batch.size()];
            if ((i + 1) % MAX_DB_BATCH_SIZE == 0 || (i + 1) == toCommit.size()) {
                executed = pstmt.executeBatch();
                assert (executed.length == batch.size());
                conn.commit();
                pstmt.clearBatch();
                for (int j = 0; j < executed.length; j++) {
                    if (executed[j] > 0) {
                        log.log(Level.FINE, "{0} updated RC DB record to {1}",
                                new Object[] { this, toCommit.get(batch.get(j)).getSummary() });
                        committed.add(batch.get(j));
                    } else
                        log.log(Level.FINE,
                                "{0} unable to update RC record {1} (executed={2}), will try insert",
                                new Object[] { this, batch.get(j), executed[j] });
                }
                batch.clear();
            }
        }
    } catch (SQLException sqle) {
        log.severe("SQLException while inserting RC record using " + cmd);
        sqle.printStackTrace();
    } finally {
        cleanup(pstmt);
        cleanup(conn);
    }

    log.log(Level.FINE, "{0} batch-committed {1}({2}) out of {3}({4})",
            new Object[] { this, committed.size(), committed, toCommit.size(), toCommit.keySet() });
    committed.addAll(this.putReconfigurationRecordIndividually(this.diff(toCommit, committed)));
    log.log(Level.FINE, "{0} committed {1}({2}) out of {3}({4})",
            new Object[] { this, committed.size(), committed, toCommit.size(), toCommit.keySet() });
    return committed;
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private boolean createReconfigurationRecordsDB(Map<String, String> nameStates, Set<NodeIDType> newActives) {
    String insertCmd = "insert into " + getRCRecordTable() + " (" + Columns.RC_GROUP_NAME.toString() + ", "
            + Columns.STRINGIFIED_RECORD.toString() + ", " + Columns.SERVICE_NAME.toString()
            + " ) values (?,?,?)";

    PreparedStatement insertRC = null;
    Connection conn = null;/*from  w  w  w .  j  a  va 2s.c  om*/
    boolean insertedAll = true;
    Set<String> batch = new HashSet<String>();
    Set<String> committed = new HashSet<String>();
    try {
        if (conn == null) {
            conn = this.getDefaultConn();
            conn.setAutoCommit(false);
            insertRC = conn.prepareStatement(insertCmd);
        }
        assert (nameStates != null && !nameStates.isEmpty());
        String rcGroupName = this.getRCGroupName(nameStates.keySet().iterator().next());
        int i = 0;
        long t1 = System.currentTimeMillis();
        for (String name : nameStates.keySet()) {
            ReconfigurationRecord<NodeIDType> record = new ReconfigurationRecord<NodeIDType>(name, -1,
                    newActives);
            /* We just directly initialize with WAIT_ACK_STOP:-1 instead of
             * starting with READY:-1 and pretending to go through the whole
             * reconfiguration protocol sequence. */
            record.setState(name, -1, RCStates.WAIT_ACK_STOP);
            insertRC.setString(1, rcGroupName);
            if (RC_RECORD_CLOB_OPTION)
                insertRC.setClob(2, new StringReader(record.toString()));
            else
                insertRC.setString(2, record.toString());
            insertRC.setString(3, name);
            insertRC.addBatch();
            batch.add(name);
            i++;
            if ((i + 1) % MAX_DB_BATCH_SIZE == 0 || (i + 1) == nameStates.size()) {
                int[] executed = insertRC.executeBatch();
                conn.commit();
                insertRC.clearBatch();
                committed.addAll(batch);
                batch.clear();
                for (int j : executed)
                    insertedAll = insertedAll && (j > 0);
                if (insertedAll)
                    log.log(Level.FINE, "{0} successfully logged the last {1} messages in {2} ms",
                            new Object[] { this, (i + 1), (System.currentTimeMillis() - t1) });
                t1 = System.currentTimeMillis();
            }
        }
    } catch (SQLException sqle) {
        log.severe("SQLException while inserting batched RC records using " + insertCmd);
        sqle.printStackTrace();
    } finally {
        cleanup(insertRC);
        cleanup(conn);
    }

    // rollback
    if (!insertedAll) {
        for (String name : nameStates.keySet())
            if (committed.contains(name))
                this.deleteReconfigurationRecord(name, 0);
    }

    return insertedAll;
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.InstallationController.java

/**
 * This method issues special blob-inserts command to the db. 
 * I had to build my own adoption of sql to make this feature.
 *//*from ww  w  .  ja va2  s . c  o  m*/

protected void issueSpecialBlobCommand(Connection conn, String originalSql) throws Exception {
    String sql = originalSql;
    //Logger.logInfo("SpecialBlob Command:" + sql);

    try {
        String valuesPart = sql.substring(sql.indexOf("VALUES") + 6).trim();
        sql = sql.substring(0, sql.indexOf("VALUES") + 6);
        //logger.info("sql:" + sql);
        //logger.info("valuesPart:" + valuesPart);

        String tableName = null;
        int blobColumn = 0;
        List columns = null;
        List columnValues = null;

        StringTokenizer st = new StringTokenizer(sql, " ");
        int i = 0;
        while (st.hasMoreTokens()) {
            String part = st.nextToken();
            //Logger.logInfo("Part: " + part);

            if (i == 1)
                blobColumn = new Integer(part).intValue();
            if (i == 4)
                tableName = part;
            if (i == 5) {
                columns = parseColumns(part);
            }

            i++;
        }

        columnValues = parseValues(valuesPart);

        String columnsString = "";
        String valuesString = "";
        Iterator columnsIterator = columns.iterator();
        while (columnsIterator.hasNext()) {
            columnsString += (columnsString.equals("")) ? (String) columnsIterator.next()
                    : "," + columnsIterator.next();
            valuesString += (valuesString.equals("")) ? "?" : ",?";
        }

        sql = "INSERT INTO " + tableName + "(" + columnsString + ") VALUES (" + valuesString + ")";

        PreparedStatement ps = conn.prepareStatement(sql);

        int index = 1;
        int loopCount = 0;
        Iterator columnValuesIterator = columnsIterator = columns.iterator();
        while (columnsIterator.hasNext()) {
            columnsIterator.next();
            String value = (String) columnValues.get(loopCount);

            if (index == 1 || value.indexOf("'") == -1) {
                ps.setInt(index, new Integer(value).intValue());
            } else if (index == blobColumn) {
                //Logger.logInfo("value:" + value);
                value = value.substring(1, value.length() - 1);
                //Logger.logInfo("value:" + value);

                if (value.indexOf("assetBlob:") > -1) {
                    String fileName = value.substring(10);
                    FileInputStream fis = new FileInputStream(fileName);

                    BLOB bl = BLOB.createTemporary(conn, true, BLOB.DURATION_CALL);
                    bl.open(BLOB.MODE_READWRITE);

                    BufferedOutputStream out = new BufferedOutputStream(bl.getBinaryOutputStream());

                    byte[] buffer = new byte[1024];
                    int len;

                    while ((len = fis.read(buffer)) >= 0)
                        out.write(buffer, 0, len);

                    out.flush();
                    fis.close();
                    out.close();

                    ps.setBlob(index, bl);
                } else {
                    CLOB cl = CLOB.createTemporary(conn, true, CLOB.DURATION_CALL);
                    cl.putString(1, value);
                    ps.setClob(index, cl);
                }
            } else if (value.indexOf("date:") > -1) {
                value = value.substring(6);
                Date date = parseDate(value, "yyyy-MM-dd HH:mm:ss");

                ps.setDate(index, new java.sql.Date(date.getTime()));
            } else {
                //Logger.logInfo("value:" + value);
                value = value.substring(1, value.length() - 1);
                //Logger.logInfo("value:" + value);
                ps.setString(index, value);
            }

            index++;
            loopCount++;
        }

        ps.executeUpdate();
    } catch (Exception ex) {
        logger.error("Command failed: " + ex.getMessage());
        logger.error("SQL: " + originalSql);
        throw ex;
    }
}

From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java

/**
 * Runs the insertCommand prepared statement.
  * <code>/*from   w ww  .j ava 2 s.c o  m*/
 *        INSERT INTO {0} (transactionId, commandType,context,prereq) VALUES (?, ?, ?, ?)    
 * </code>
 *
 *@param stmtProvider
 *         factory and cache of PreparedStatments
 *@param connection
 *          connection to underlying database
 *
 *@param transactionId template parameter
 *@param commandType template parameter
 *@param context template parameter
 *@param preReq template parameter
 *
 *@param transactionTableName template parameter
 *@return  int
 *@throws  org.openanzo.jdbc.utils.RdbException
 */
public static int insertCommand(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider,
        final java.sql.Connection connection, long transactionId, String commandType, java.sql.Clob context,
        java.sql.Clob preReq, String transactionTableName) throws org.openanzo.jdbc.utils.RdbException {
    java.sql.PreparedStatement ps = null;
    //long startTimer=System.currentTimeMillis();
    try {
        ps = stmtProvider.getPreparedSQLStatement(insertCommand, new String[] { transactionTableName },
                connection);
        int argc = 1;
        ps.setLong(argc++, transactionId);
        if (commandType == null) {
            ps.setNull(argc++, java.sql.Types.VARCHAR);
        } else {
            ps.setString(argc++, commandType);
        }
        if (context == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, context);
        }
        if (preReq == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, preReq);
        }
        int counter = 0;
        try {
            counter = ps.executeUpdate();
        } catch (java.sql.SQLException sqle) {
            if (sqle.getErrorCode() == 1205) {
                int retries = 0;
                while (retries < 5) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ie) {
                        throw sqle;
                    }
                    try {
                        counter = ps.executeUpdate();
                        break;
                    } catch (java.sql.SQLException sqleInner) {
                        if (sqleInner.getErrorCode() == 1205) {
                            retries++;
                        } else {
                            throw sqleInner;
                        }
                    }
                }
                if (retries >= 5) {
                    throw sqle;
                }
            } else {
                throw sqle;
            }
        }
        return counter;

    } catch (java.sql.SQLException e) {
        throw new org.openanzo.jdbc.utils.RdbException(
                org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "insertCommand",
                stmtProvider.getSqlString(insertCommand),
                "" + "transactionId=" + (transactionId) + "," + "commandType="
                        + ((commandType != null) ? commandType.toString() : "null") + "," + "context="
                        + ((context != null) ? context.toString() : "null") + "," + "preReq="
                        + ((preReq != null) ? preReq.toString() : "null"),
                "" + "transactionTableName="
                        + ((transactionTableName != null) ? transactionTableName.toString() : "null"));
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (java.sql.SQLException sqle) {
                if (log.isDebugEnabled())
                    log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement",
                            sqle);
            }
        }
        //long endtimer=(System.currentTimeMillis()-startTimer);
        //if(endtimer>CUTOFF)System.out.println("[insertCommand]"+endtimer);
    }
}

From source file:org.openanzo.jdbc.container.sql.TransactionSQL.java

/**
 * Runs the updateCommand prepared statement.
  * <code>//from   ww w . j a  va2s.co m
 *        UPDATE {0} set transactionId=?,commandType=?,context=?,preReq=? where id=?    
 * </code>
 *
 *@param stmtProvider
 *         factory and cache of PreparedStatments
 *@param connection
 *          connection to underlying database
 *
 *@param transactionId template parameter
 *@param commandType template parameter
 *@param context template parameter
 *@param preReq template parameter
 *@param id template parameter
 *
 *@param transactionTableName template parameter
 *@return  int
 *@throws  org.openanzo.jdbc.utils.RdbException
 */
public static int updateCommand(final org.openanzo.jdbc.utils.PreparedStatementProvider stmtProvider,
        final java.sql.Connection connection, long transactionId, String commandType, java.sql.Clob context,
        java.sql.Clob preReq, long id, String transactionTableName)
        throws org.openanzo.jdbc.utils.RdbException {
    java.sql.PreparedStatement ps = null;
    //long startTimer=System.currentTimeMillis();
    try {
        ps = stmtProvider.getPreparedSQLStatement(updateCommand, new String[] { transactionTableName },
                connection);
        int argc = 1;
        ps.setLong(argc++, transactionId);
        if (commandType == null) {
            ps.setNull(argc++, java.sql.Types.VARCHAR);
        } else {
            ps.setString(argc++, commandType);
        }
        if (context == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, context);
        }
        if (preReq == null) {
            ps.setNull(argc++, java.sql.Types.CLOB);
        } else {
            ps.setClob(argc++, preReq);
        }
        ps.setLong(argc++, id);
        int counter = 0;
        try {
            counter = ps.executeUpdate();
        } catch (java.sql.SQLException sqle) {
            if (sqle.getErrorCode() == 1205) {
                int retries = 0;
                while (retries < 5) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ie) {
                        throw sqle;
                    }
                    try {
                        counter = ps.executeUpdate();
                        break;
                    } catch (java.sql.SQLException sqleInner) {
                        if (sqleInner.getErrorCode() == 1205) {
                            retries++;
                        } else {
                            throw sqleInner;
                        }
                    }
                }
                if (retries >= 5) {
                    throw sqle;
                }
            } else {
                throw sqle;
            }
        }
        return counter;

    } catch (java.sql.SQLException e) {
        throw new org.openanzo.jdbc.utils.RdbException(
                org.openanzo.exceptions.ExceptionConstants.RDB.FAILED_EXECUTING_SQL, e, "updateCommand",
                stmtProvider.getSqlString(updateCommand),
                "" + "transactionId=" + (transactionId) + "," + "commandType="
                        + ((commandType != null) ? commandType.toString() : "null") + "," + "context="
                        + ((context != null) ? context.toString() : "null") + "," + "preReq="
                        + ((preReq != null) ? preReq.toString() : "null") + "," + "id=" + (id),
                "" + "transactionTableName="
                        + ((transactionTableName != null) ? transactionTableName.toString() : "null"));
    } finally {
        if (ps != null) {
            try {
                ps.close();
            } catch (java.sql.SQLException sqle) {
                if (log.isDebugEnabled())
                    log.debug(org.openanzo.exceptions.LogUtils.RDB_MARKER, "Error closing prepared statement",
                            sqle);
            }
        }
        //long endtimer=(System.currentTimeMillis()-startTimer);
        //if(endtimer>CUTOFF)System.out.println("[updateCommand]"+endtimer);
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Set the given value as a parameter to the statement.
 *//*from   w  w  w.  j  a  va  2 s . c o m*/
public void setClob(PreparedStatement stmnt, int idx, Clob val, Column col) throws SQLException {
    stmnt.setClob(idx, val);
}