Example usage for java.sql PreparedStatement setBytes

List of usage examples for java.sql PreparedStatement setBytes

Introduction

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

Prototype

void setBytes(int parameterIndex, byte x[]) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java array of bytes.

Usage

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *//*w  ww  .  jav  a 2s  . c om*/
public void insertImage(ImageData imageData, boolean isResized, Connection conn) throws SQLException {
    PreparedStatement stmt = null;
    try {
        stmt = conn.prepareStatement(STATEMENT_INSERT_FILE_DATA);
        stmt.setInt(1, imageData.fileVersionId);
        stmt.setInt(2, isResized ? imageData.width : 0);
        stmt.setInt(3, imageData.width);
        stmt.setInt(4, imageData.height);
        stmt.setBytes(5, imageData.data);
        stmt.executeUpdate();
    } finally {
        DatabaseConnection.closeStatement(stmt);
    }
}

From source file:org.opencms.db.generic.CmsProjectDriver.java

/**
 * @see org.opencms.db.I_CmsProjectDriver#createPublishJob(org.opencms.db.CmsDbContext, org.opencms.publish.CmsPublishJobInfoBean)
 *//*from   w  w  w.j a  v  a 2  s. c  om*/
public void createPublishJob(CmsDbContext dbc, CmsPublishJobInfoBean publishJob) throws CmsDataAccessException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        CmsPublishJobInfoBean currentJob = readPublishJob(dbc, publishJob.getPublishHistoryId());
        LOG.error("wanted to write: " + publishJob);
        LOG.error("already on db: " + currentJob);
        return;
    } catch (CmsDbEntryNotFoundException e) {
        // ok, this is the expected behavior
    }
    try {
        conn = m_sqlManager.getConnection(dbc);
        stmt = m_sqlManager.getPreparedStatement(conn, "C_PUBLISHJOB_CREATE");

        stmt.setString(1, publishJob.getPublishHistoryId().toString());
        stmt.setString(2, publishJob.getProjectId().toString());
        stmt.setString(3, publishJob.getProjectName());
        stmt.setString(4, publishJob.getUserId().toString());
        stmt.setString(5, publishJob.getLocale().toString());
        stmt.setInt(6, publishJob.getFlags());
        stmt.setInt(7, publishJob.getSize());
        stmt.setLong(8, publishJob.getEnqueueTime());
        stmt.setLong(9, publishJob.getStartTime());
        stmt.setLong(10, publishJob.getFinishTime());

        byte[] publishList = internalSerializePublishList(publishJob.getPublishList());
        if (publishList.length < 2000) {
            stmt.setBytes(11, publishList);
        } else {
            stmt.setBinaryStream(11, new ByteArrayInputStream(publishList), publishList.length);
        }

        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } catch (IOException e) {
        throw new CmsDbIoException(Messages.get().container(Messages.ERR_SERIALIZING_PUBLISHLIST_1,
                publishJob.getPublishHistoryId().toString()), e);
    } finally {
        m_sqlManager.closeAll(dbc, conn, stmt, null);
    }
}

From source file:org.opencms.db.generic.CmsVfsDriver.java

/**
 * @see org.opencms.db.I_CmsVfsDriver#writeContent(org.opencms.db.CmsDbContext, org.opencms.util.CmsUUID, byte[])
 *//*from  w  w w . j  ava  2s. com*/
public void writeContent(CmsDbContext dbc, CmsUUID resourceId, byte[] content) throws CmsDataAccessException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = m_sqlManager.getConnection(dbc);
        stmt = m_sqlManager.getPreparedStatement(conn, dbc.currentProject(), "C_OFFLINE_CONTENTS_UPDATE");
        // update the file content in the database.
        if (content.length < 2000) {
            stmt.setBytes(1, content);
        } else {
            stmt.setBinaryStream(1, new ByteArrayInputStream(content), content.length);
        }
        stmt.setString(2, resourceId.toString());
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } finally {
        m_sqlManager.closeAll(dbc, conn, stmt, null);
    }
}

From source file:org.opencms.db.generic.CmsVfsDriver.java

/**
* @see org.opencms.db.I_CmsVfsDriver#createContent(CmsDbContext, CmsUUID, CmsUUID, byte[])
*//*from   w  w w .jav  a2s . c o m*/
public void createContent(CmsDbContext dbc, CmsUUID projectId, CmsUUID resourceId, byte[] content)
        throws CmsDataAccessException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = m_sqlManager.getConnection(dbc);
        // create new offline content
        stmt = m_sqlManager.getPreparedStatement(conn, "C_OFFLINE_CONTENTS_WRITE");
        stmt.setString(1, resourceId.toString());
        if (content.length < 2000) {
            stmt.setBytes(2, content);
        } else {
            stmt.setBinaryStream(2, new ByteArrayInputStream(content), content.length);
        }
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } finally {
        m_sqlManager.closeAll(dbc, conn, stmt, null);
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcTransactionalStorage.java

protected String storeMessageInDatabase(Connection conn, String messageId, String correlationId,
        Timestamp receivedDateTime, String comments, String label, Serializable message)
        throws IOException, SQLException, JdbcException, SenderException {
    PreparedStatement stmt = null;
    try {/*from w  w  w  .  j  ava 2 s.co  m*/
        IDbmsSupport dbmsSupport = getDbmsSupport();
        if (log.isDebugEnabled())
            log.debug("preparing insert statement [" + insertQuery + "]");
        if (!dbmsSupport.mustInsertEmptyBlobBeforeData()) {
            stmt = conn.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
        } else {
            stmt = conn.prepareStatement(insertQuery);
        }
        stmt.clearParameters();
        int parPos = 0;

        if (StringUtils.isNotEmpty(getTypeField())) {
            stmt.setString(++parPos, type);
        }
        if (StringUtils.isNotEmpty(getSlotId())) {
            stmt.setString(++parPos, getSlotId());
        }
        if (StringUtils.isNotEmpty(getHostField())) {
            stmt.setString(++parPos, host);
        }
        if (StringUtils.isNotEmpty(getLabelField())) {
            stmt.setString(++parPos, label);
        }
        stmt.setString(++parPos, messageId);
        stmt.setString(++parPos, correlationId);
        stmt.setTimestamp(++parPos, receivedDateTime);
        stmt.setString(++parPos, comments);
        if (type.equalsIgnoreCase(TYPE_MESSAGELOG_PIPE) || type.equalsIgnoreCase(TYPE_MESSAGELOG_RECEIVER)) {
            if (getRetention() < 0) {
                stmt.setTimestamp(++parPos, null);
            } else {
                Date date = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(date);
                cal.add(Calendar.DAY_OF_MONTH, getRetention());
                stmt.setTimestamp(++parPos, new Timestamp(cal.getTime().getTime()));
            }
        } else {
            stmt.setTimestamp(++parPos, null);
        }

        if (!isStoreFullMessage()) {
            if (isOnlyStoreWhenMessageIdUnique()) {
                stmt.setString(++parPos, messageId);
                stmt.setString(++parPos, slotId);
            }
            stmt.execute();
            return null;
        }
        if (!dbmsSupport.mustInsertEmptyBlobBeforeData()) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            if (isBlobsCompressed()) {
                DeflaterOutputStream dos = new DeflaterOutputStream(out);
                ObjectOutputStream oos = new ObjectOutputStream(dos);
                oos.writeObject(message);
                dos.close();
            } else {
                ObjectOutputStream oos = new ObjectOutputStream(out);
                oos.writeObject(message);
            }

            stmt.setBytes(++parPos, out.toByteArray());
            if (isOnlyStoreWhenMessageIdUnique()) {
                stmt.setString(++parPos, messageId);
                stmt.setString(++parPos, slotId);
            }
            stmt.execute();
            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                return rs.getString(1);
            } else {
                return null;
            }
        }
        if (isOnlyStoreWhenMessageIdUnique()) {
            stmt.setString(++parPos, messageId);
            stmt.setString(++parPos, slotId);
        }
        stmt.execute();
        int updateCount = stmt.getUpdateCount();
        if (log.isDebugEnabled())
            log.debug("update count for insert statement: " + updateCount);
        if (updateCount > 0) {
            if (log.isDebugEnabled())
                log.debug("preparing select statement [" + selectKeyQuery + "]");
            stmt = conn.prepareStatement(selectKeyQuery);
            ResultSet rs = null;
            try {
                // retrieve the key
                rs = stmt.executeQuery();
                if (!rs.next()) {
                    throw new SenderException("could not retrieve key of stored message");
                }
                String newKey = rs.getString(1);
                rs.close();

                // and update the blob
                if (log.isDebugEnabled())
                    log.debug("preparing update statement [" + updateBlobQuery + "]");
                stmt = conn.prepareStatement(updateBlobQuery);
                stmt.clearParameters();
                stmt.setString(1, newKey);

                rs = stmt.executeQuery();
                if (!rs.next()) {
                    throw new SenderException("could not retrieve row for stored message [" + messageId + "]");
                }
                //                  String newKey = rs.getString(1);
                //                  BLOB blob = (BLOB)rs.getBlob(2);
                Object blobHandle = dbmsSupport.getBlobUpdateHandle(rs, 1);
                OutputStream out = dbmsSupport.getBlobOutputStream(rs, 1, blobHandle);
                //               OutputStream out = JdbcUtil.getBlobUpdateOutputStream(rs,1);
                if (isBlobsCompressed()) {
                    DeflaterOutputStream dos = new DeflaterOutputStream(out);
                    ObjectOutputStream oos = new ObjectOutputStream(dos);
                    oos.writeObject(message);
                    oos.close();
                    dos.close();
                } else {
                    ObjectOutputStream oos = new ObjectOutputStream(out);
                    oos.writeObject(message);
                    oos.close();
                }
                out.close();
                dbmsSupport.updateBlob(rs, 1, blobHandle);
                return newKey;

            } finally {
                if (rs != null) {
                    rs.close();
                }
            }
        } else {
            if (isOnlyStoreWhenMessageIdUnique()) {
                return "already there";
            } else {
                throw new SenderException(
                        "update count for update statement not greater than 0 [" + updateCount + "]");
            }
        }

    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "UPDATE" on the given tableName with attribute values
 * and where clause.//from  w ww  .j  ava2s  .  c  o m
 * 
 * @param tableName
 * @param attributeNameValue
 * @param whereClause
 * @return
 * @throws SQLException
 */
public int updateRow(String tableName, Map attributeNameValue, String whereClause, String dbType)
        throws SQLException {

    StringBuffer stmt = new StringBuffer();
    PreparedStatement prepStmt = null;
    int rowsUpdated = 0;
    Object attribute = null;
    Iterator itr = null;
    String[] key = new String[attributeNameValue.size()];
    int count = 0;

    stmt.append("UPDATE " + tablePrefix_ + tableName.trim() + " SET ");

    itr = attributeNameValue.keySet().iterator();

    while (itr.hasNext()) {
        key[count] = (String) itr.next();
        stmt.append(key[count++] + " = ?,");
    }

    /*
     * for (int i = 0; i < attributeNames.size(); i++) {
     * stmt.append(attributeNames.get(i) + " = ?,"); }
     */

    stmt = stmt.deleteCharAt(stmt.length() - 1);

    if (whereClause != null && !"".equals(whereClause)) {
        stmt.append(" WHERE ");
        stmt.append(whereClause);
    }

    // stmt = stmt.deleteCharAt(stmt.length());

    log.debug("************ UPDATE QUERY ************");
    log.debug(stmt.toString());
    log.debug("**************************************");
    try {

        String statement = new GenericSQLModifier(dbType, false).modifySQL(stmt.toString());

        prepStmt = sqlConnection_.prepareStatement(statement);

        itr = attributeNameValue.keySet().iterator();

        for (count = 0; count < key.length; count++) {

            attribute = attributeNameValue.get(key[count]);

            if (attribute instanceof String) {
                prepStmt.setString(count + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(count + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(count + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(count + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(count + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(count + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(count + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(count + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(count + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(count + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(count + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(count + 1, (Timestamp) attribute);
            }
        }

        rowsUpdated = prepStmt.executeUpdate();
    } catch (Exception e) {
        log.error("Exception @ updateRow: " + e.getMessage());
    } finally {
        prepStmt.close();
    }

    return rowsUpdated;

}

From source file:nl.nn.adapterframework.jdbc.JdbcFacade.java

protected void applyParameters(PreparedStatement statement, ParameterValueList parameters)
        throws SQLException, SenderException {
    // statement.clearParameters();

    /*//  www.j  a va2s.co  m
          // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation.
          int senderParameterCount = parameters.size();
          int statementParameterCount = statement.getParameterMetaData().getParameterCount();
          if (statementParameterCount<senderParameterCount) {
             throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]");
          }
    */

    for (int i = 0; i < parameters.size(); i++) {
        ParameterValue pv = parameters.getParameterValue(i);
        String paramType = pv.getDefinition().getType();
        Object value = pv.getValue();
        //      log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]");

        if (Parameter.TYPE_DATE.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.DATE);
            } else {
                statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_DATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIME);
            } else {
                statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_NUMBER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.NUMERIC);
            } else {
                statement.setDouble(i + 1, ((Number) value).doubleValue());
            }
        } else if (Parameter.TYPE_INTEGER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.INTEGER);
            } else {
                statement.setInt(i + 1, (Integer) value);
            }
        } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
            if (value instanceof FileInputStream) {
                FileInputStream fis = (FileInputStream) value;
                long len = 0;
                try {
                    len = fis.getChannel().size();
                } catch (IOException e) {
                    log.warn(getLogPrefix() + "could not determine file size", e);
                }
                statement.setBinaryStream(i + 1, fis, (int) len);
            } else if (value instanceof ByteArrayInputStream) {
                ByteArrayInputStream bais = (ByteArrayInputStream) value;
                long len = bais.available();
                statement.setBinaryStream(i + 1, bais, (int) len);
            } else {
                throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                        + "] for parameter [" + pv.getDefinition().getName() + "]");
            }
        } else if ("string2bytes".equals(paramType)) {
            statement.setBytes(i + 1, ((String) value).getBytes());
        } else if ("bytes".equals(paramType)) {
            statement.setBytes(i + 1, (byte[]) value);
        } else {
            statement.setString(i + 1, (String) value);
        }
    }
}

From source file:org.sentinel.instrumentationserver.metadata.MetadataDAO.java

/**
 * Save the metadata from one XML element in the database.
 *//*from  w w w.j a v a  2  s  .  c  om*/
public void saveMetadataFromXmlElement(Node applicationNode) {
    String LOGO_BASE_URI = "https://f-droid.org/repo/icons/";
    String APP_BASE_URI = "https://f-droid.org/repo/";
    String sqlStatementGetMetadataFromXml = QueryBuilder.getQueryToSaveMetadataFromXmlElement();
    PreparedStatement preparedStatement;
    try {
        preparedStatement = databaseConnection.prepareStatement(sqlStatementGetMetadataFromXml);

        Element applicationNodeElement = null;
        if (applicationNode instanceof Element) {
            applicationNodeElement = (Element) applicationNode;
        }

        String logo = null;
        String appName = null;
        String packageName = null;
        String appUrl = null;
        String summary = null;
        String description = null;
        String license = null;
        String appCategory = null;
        String webLink = null;
        String sourceCodeLink = null;
        String marketVersion = null;
        String sha256Hash = null;
        double sizeInBytes = 0;
        String sdkVersion = null;
        String permissions = null;
        String features = null;

        if (applicationNodeElement.getElementsByTagName("icon").item(0) != null) {
            logo = LOGO_BASE_URI + applicationNodeElement.getElementsByTagName("icon").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("name").item(0) != null) {
            appName = applicationNodeElement.getElementsByTagName("name").item(0).getTextContent();
        }
        if (applicationNodeElement.getAttribute("id") != null) {
            packageName = applicationNodeElement.getAttribute("id");
        }
        if (applicationNodeElement.getElementsByTagName("apkname").item(0) != null) {
            appUrl = APP_BASE_URI
                    + applicationNodeElement.getElementsByTagName("apkname").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("summary").item(0) != null) {
            summary = applicationNodeElement.getElementsByTagName("summary").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("desc").item(0) != null) {
            description = applicationNodeElement.getElementsByTagName("desc").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("license").item(0) != null) {
            license = applicationNodeElement.getElementsByTagName("license").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("category").item(0) != null) {
            appCategory = applicationNodeElement.getElementsByTagName("category").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("web").item(0) != null) {
            webLink = applicationNodeElement.getElementsByTagName("web").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("source").item(0) != null) {
            sourceCodeLink = applicationNodeElement.getElementsByTagName("source").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("marketversion").item(0) != null) {
            marketVersion = applicationNodeElement.getElementsByTagName("marketversion").item(0)
                    .getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("hash").item(0) != null) {
            sha256Hash = applicationNodeElement.getElementsByTagName("hash").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("size").item(0) != null) {
            sizeInBytes = Double
                    .parseDouble(applicationNodeElement.getElementsByTagName("size").item(0).getTextContent());
        }
        if (applicationNodeElement.getElementsByTagName("sdkver").item(0) != null) {
            sdkVersion = applicationNodeElement.getElementsByTagName("sdkver").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("permissions").item(0) != null) {
            permissions = applicationNodeElement.getElementsByTagName("permissions").item(0).getTextContent();
        }
        if (applicationNodeElement.getElementsByTagName("features").item(0) != null) {
            features = applicationNodeElement.getElementsByTagName("features").item(0).getTextContent();
        }

        byte[] logoBytes = fetchLogo(logo);

        preparedStatement.setBytes(1, logoBytes);
        preparedStatement.setString(2, appName);
        preparedStatement.setString(3, packageName);
        preparedStatement.setString(4, appUrl);
        preparedStatement.setString(5, summary);
        preparedStatement.setString(6, description);
        preparedStatement.setString(7, license);
        preparedStatement.setString(8, appCategory);
        preparedStatement.setString(9, webLink);
        preparedStatement.setString(10, sourceCodeLink);
        preparedStatement.setString(11, marketVersion);
        preparedStatement.setString(12, sha256Hash);
        preparedStatement.setDouble(13, sizeInBytes);
        preparedStatement.setString(14, sdkVersion);
        preparedStatement.setString(15, permissions);
        preparedStatement.setString(16, features);
        preparedStatement.setString(17, sha256Hash);

        preparedStatement.execute();
        preparedStatement.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

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

/**
 * Set the given value as a parameter to the statement.
 *//*w  w  w.  j a  va2  s .  com*/
public void setBytes(PreparedStatement stmnt, int idx, byte[] val, Column col) throws SQLException {
    if (useSetBytesForBlobs)
        stmnt.setBytes(idx, val);
    else
        setBinaryStream(stmnt, idx, new ByteArrayInputStream(val), val.length, col);
}

From source file:org.opencms.db.generic.CmsVfsDriver.java

/**
 * @see org.opencms.db.I_CmsVfsDriver#createOnlineContent(org.opencms.db.CmsDbContext, org.opencms.util.CmsUUID, byte[], int, boolean, boolean)
 */// w w  w.  ja v  a  2  s  . c  om
public void createOnlineContent(CmsDbContext dbc, CmsUUID resourceId, byte[] contents, int publishTag,
        boolean keepOnline, boolean needToUpdateContent) throws CmsDataAccessException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = m_sqlManager.getConnection(dbc);
        boolean dbcHasProjectId = (dbc.getProjectId() != null) && !dbc.getProjectId().isNullUUID();

        if (needToUpdateContent || dbcHasProjectId) {
            if (dbcHasProjectId || !OpenCms.getSystemInfo().isHistoryEnabled()) {
                // remove the online content for this resource id
                stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_DELETE");
                stmt.setString(1, resourceId.toString());
                stmt.executeUpdate();
                m_sqlManager.closeAll(dbc, null, stmt, null);
            } else {
                // put the online content in the history, only if explicit requested
                stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_HISTORY");
                stmt.setString(1, resourceId.toString());
                stmt.executeUpdate();
                m_sqlManager.closeAll(dbc, null, stmt, null);
            }

            // create new online content
            stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_WRITE");

            stmt.setString(1, resourceId.toString());
            if (contents.length < 2000) {
                stmt.setBytes(2, contents);
            } else {
                stmt.setBinaryStream(2, new ByteArrayInputStream(contents), contents.length);
            }
            stmt.setInt(3, publishTag);
            stmt.setInt(4, publishTag);
            stmt.setInt(5, keepOnline ? 1 : 0);
            stmt.executeUpdate();
            m_sqlManager.closeAll(dbc, null, stmt, null);
        } else {
            // update old content entry
            stmt = m_sqlManager.getPreparedStatement(conn, "C_HISTORY_CONTENTS_UPDATE");
            stmt.setInt(1, publishTag);
            stmt.setString(2, resourceId.toString());
            stmt.executeUpdate();
            m_sqlManager.closeAll(dbc, null, stmt, null);

            if (!keepOnline) {
                // put the online content in the history 
                stmt = m_sqlManager.getPreparedStatement(conn, "C_ONLINE_CONTENTS_HISTORY");
                stmt.setString(1, resourceId.toString());
                stmt.executeUpdate();
                m_sqlManager.closeAll(dbc, null, stmt, null);
            }
        }
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } finally {
        m_sqlManager.closeAll(dbc, conn, stmt, null);
    }
}