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:com.glaf.core.execution.FileExecutionHelper.java

public void save(Connection connection, String serviceKey, File file) {
    String sql = " insert into " + BlobItemDomainFactory.TABLENAME
            + " (ID_, BUSINESSKEY_, FILEID_, SERVICEKEY_, NAME_, TYPE_, FILENAME_, PATH_, LASTMODIFIED_, LOCKED_, STATUS_, DATA_, CREATEBY_, CREATEDATE_)"
            + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
    PreparedStatement psmt = null;
    try {//from   ww w  .j a  va 2  s . c  om
        psmt = connection.prepareStatement(sql);
        psmt.setString(1, UUID32.getUUID());
        psmt.setString(2, serviceKey);
        psmt.setString(3, DigestUtils.md5Hex(file.getAbsolutePath()));
        psmt.setString(4, serviceKey);
        psmt.setString(5, file.getName());
        psmt.setString(6, "Execution");
        psmt.setString(7, file.getAbsolutePath());
        psmt.setString(8, file.getAbsolutePath());
        psmt.setLong(9, file.lastModified());
        psmt.setInt(10, 0);
        psmt.setInt(11, 1);
        psmt.setBytes(12, FileUtils.getBytes(file));
        psmt.setString(13, "system");
        psmt.setTimestamp(14, DateUtils.toTimestamp(new java.util.Date()));
        psmt.executeUpdate();
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
    }
}

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.feature.AbstractFeatureDAO.java

@Override
public List<ProfileFeature> updateProfileFeatures(List<ProfileFeature> features, int profileId)
        throws FeatureManagerDAOException {

    Connection conn;// www.j a v  a2s  . c  om
    PreparedStatement stmt = null;
    int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();

    try {
        conn = this.getConnection();
        String query = "UPDATE DM_PROFILE_FEATURES SET CONTENT = ? WHERE PROFILE_ID = ? AND FEATURE_CODE = ? AND"
                + " TENANT_ID = ?";

        stmt = conn.prepareStatement(query);
        for (ProfileFeature feature : features) {
            stmt.setBytes(1, PolicyManagerUtil.getBytes(feature.getContent()));
            stmt.setInt(2, profileId);
            stmt.setString(3, feature.getFeatureCode());
            stmt.setInt(4, tenantId);
            stmt.addBatch();
            //Not adding the logic to check the size of the stmt and execute if the size records added is over 1000
        }
        stmt.executeBatch();

    } catch (SQLException | IOException e) {
        throw new FeatureManagerDAOException("Error occurred while adding the feature list to the database.",
                e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, null);
    }
    return features;
}

From source file:org.apache.ddlutils.platform.postgresql.PostgreSqlPlatform.java

/**
 * {@inheritDoc}/*  w  ww.  j a  v  a 2 s.co m*/
 */
protected void setObject(PreparedStatement statement, int sqlIndex, DynaBean dynaBean, SqlDynaProperty property)
        throws SQLException {
    int typeCode = property.getColumn().getTypeCode();
    Object value = dynaBean.get(property.getName());

    // PostgreSQL doesn't like setNull for BYTEA columns
    if (value == null) {
        switch (typeCode) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
        case Types.BLOB:
            statement.setBytes(sqlIndex, null);
            break;
        default:
            statement.setNull(sqlIndex, typeCode);
            break;
        }
    } else {
        super.setObject(statement, sqlIndex, dynaBean, property);
    }
}

From source file:jm.web.Archivo.java

/**
 * Guarda el registro del nombre y el archivo binario en una tabla de la base de datos.
 * @param nombre. Nombre del archivo subido.
 * @param archivo. Ruta del archivo subido.
 * @return Retorna true o false si se guarda o no el archivo en la DB.
 */// w  w  w  .  j a  v a 2  s.c  om
public boolean setArchivoDB(String tabla, String campoNombre, String campoBytea, String clave, String nombre,
        File archivo) {
    boolean r = false;
    try {
        Connection conexion = this.getConexion();
        PreparedStatement ps = conexion.prepareStatement("UPDATE " + tabla + " SET " + campoNombre + "='"
                + nombre + "', " + campoBytea + "=? WHERE " + tabla.replace("tbl_", "id_") + "=" + clave + ";");
        conexion.setAutoCommit(false);
        FileInputStream archivoIS = new FileInputStream(this._archivo);
        try {
            /*ps.setBinaryStream(1, archivoIS, (int)archivo.length());*/
            byte buffer[] = new byte[(int) archivo.length()];
            archivoIS.read(buffer);
            ps.setBytes(1, buffer);

            ps.executeUpdate();
            conexion.commit();
            r = true;
        } catch (Exception e) {
            this._error = e.getMessage();
            e.printStackTrace();
        } finally {
            archivoIS.close();
            ps.close();
        }

    } catch (Exception e) {
        this._error = e.getMessage();
        e.printStackTrace();
    }
    return r;
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    Connection conn = Javaconnect.ConnecrDb();
    PreparedStatement pst = null;
    ResultSet rs = null;//from  www  . ja v a  2 s.c om
    try {
        //            String sql = "INSERT INTO ExcelData (Image) VALUES (?)";
        String sql = "Update ExcelData SET Image = ? ";
        pst = conn.prepareStatement(sql);

        pst.setBytes(1, person_image);

        pst.execute();

        System.out.println(person_image);

        JOptionPane.showMessageDialog(null, "Update Image");

        getImage();

    } catch (SQLException ex) {
        Logger.getLogger(frmSelectImage.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pst);
        DbUtils.closeQuietly(conn);
    }
}

From source file:org.theospi.portfolio.presentation.model.impl.HibernatePresentationProperties.java

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, Types.VARBINARY);
    } else {//from   w  w w.  j a va2  s  . com
        ElementBean elementBean = (ElementBean) value;
        Document doc = new Document();
        Element rootElement = elementBean.getBaseElement();
        rootElement.detach();
        doc.setRootElement(rootElement);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLOutputter xmlOutputter = new XMLOutputter();
        try {
            xmlOutputter.output(doc, out);
        } catch (IOException e) {
            throw new HibernateException(e);
        }
        st.setBytes(index, out.toByteArray());
    }

}

From source file:org.sakaiproject.metaobj.shared.model.impl.HibernateStructuredArtifact.java

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, Types.VARBINARY);
    } else {//from  w  ww  .  j ava  2 s.c  om
        StructuredArtifact artifact = (StructuredArtifact) value;
        Document doc = new Document();
        Element rootElement = artifact.getBaseElement();
        rootElement.detach();
        doc.setRootElement(rootElement);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        XMLOutputter xmlOutputter = new XMLOutputter();
        try {
            xmlOutputter.output(doc, out);
        } catch (IOException e) {
            throw new HibernateException(e);
        }
        st.setBytes(index, out.toByteArray());
    }

}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void storeSharePaticipants(Connection con, ShareMetaData smd)
        throws SQLException, PersistanceException {
    Iterator<String> it = smd.shareParticipants.getAliases();

    Statement s = con.createStatement();
    s.executeUpdate(DROP_SPL);//from   w  w w .ja va 2  s.  co  m
    s.executeUpdate(CREATE_SPL);
    s.close();
    PreparedStatement insert = con.prepareStatement(INSERT_SPL);
    while (it.hasNext()) {
        String alias = it.next();
        PublicKey pKey = smd.shareParticipants.getPublicKey(alias);
        insert.setString(1, alias);
        insert.setBytes(2, pKey.getEncoded());
        int i = insert.executeUpdate();
        logger.debug("Inserted " + i + " rows of shareparticipants");
        insert.clearParameters();
    }
    if (insert != null) {
        try {
            insert.close();
        } catch (Exception e) {
            logger.warn("Could not close Statement", e);
        }
    }
    storeSignature(con, smd.shareParticipants.getSignature());
}

From source file:com.fluidops.iwb.wiki.WikiSQLStorageBase.java

@Override
protected void storeWikiContent(URI resource, String content, WikiRevision revision) throws IOException {
    PreparedStatement prep = null;
    try {//ww w .  j ava 2  s  .c o m
        Connection conn = getConnection();
        prep = conn.prepareStatement("insert into revisions values (?, ?, ?, ?, ?, ?, ?);");

        prep.setString(1, resource.stringValue());
        prep.setLong(2, revision.date.getTime());
        prep.setLong(3, revision.size);
        prep.setString(4, revision.comment);
        prep.setString(5, revision.user);
        prep.setString(6, revision.security);
        if (com.fluidops.iwb.util.Config.getConfig().getCompressWikiInDatabase())
            prep.setBytes(7, gzip(content));
        else
            prep.setString(7, content);

        prep.execute();
        SQL.monitorWrite();
    } catch (SQLException e) {
        SQL.monitorWriteFailure();
        throw new IOException("Storing wiki content failed.", e);
    } finally {
        SQL.closeQuietly(prep);
    }
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

public void store(String key, CacheEntry entry) {
    logger.fine("Store: " + key);

    Lock lock = lockSource.getWriteLock(key);
    lock.lock();/* www . j av a  2  s .  c  o m*/
    try {
        Connection connection = connect();
        if (connection == null)
            return;

        try {
            boolean tryInsert = true;

            // Try updating this key

            String sql = "UPDATE " + cacheTableName
                    + " SET data=?, media_type=?, language=?, character_set=?, encoding=?, modification_date=?, tag=?, headers=?, expiration_date=?, document_modification_date=? WHERE key=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            try {
                statement.setBytes(1,
                        entry.getString() != null ? entry.getString().getBytes() : entry.getBytes());
                statement.setString(2, entry.getMediaType() != null ? entry.getMediaType().getName() : null);
                statement.setString(3, entry.getLanguage() != null ? entry.getLanguage().getName() : null);
                statement.setString(4,
                        entry.getCharacterSet() != null ? entry.getCharacterSet().getName() : null);
                statement.setString(5, entry.getEncoding() != null ? entry.getEncoding().getName() : null);
                statement.setTimestamp(6,
                        entry.getModificationDate() != null
                                ? new Timestamp(entry.getModificationDate().getTime())
                                : null);
                statement.setString(7, entry.getTag() != null ? entry.getTag().format() : null);
                statement.setString(8, entry.getHeaders() == null ? "" : serializeHeaders(entry.getHeaders()));
                statement.setTimestamp(9,
                        entry.getExpirationDate() != null ? new Timestamp(entry.getExpirationDate().getTime())
                                : null);
                statement.setTimestamp(10,
                        entry.getDocumentModificationDate() != null
                                ? new Timestamp(entry.getDocumentModificationDate().getTime())
                                : null);
                statement.setString(11, key);
                if (!statement.execute() && statement.getUpdateCount() > 0) {
                    logger.fine("Updated " + key);

                    // Update worked, so no need to try insertion

                    tryInsert = false;
                }
            } finally {
                statement.close();
            }

            if (tryInsert) {
                // Try inserting this key

                // But first make sure we have room...

                int size = countEntries(connection);
                if (size >= maxSize) {
                    prune();

                    size = countEntries(connection);
                    if (size >= maxSize) {
                        logger.fine("No room in cache (" + size + ", " + maxSize + ")");
                        return;
                    }
                }

                // delete( connection, key );

                sql = "INSERT INTO " + cacheTableName
                        + " (key, data, media_type, language, character_set, encoding, modification_date, tag, headers, expiration_date, document_modification_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                statement = connection.prepareStatement(sql);
                try {
                    statement.setString(1, key);
                    statement.setBytes(2,
                            entry.getString() != null ? entry.getString().getBytes() : entry.getBytes());
                    statement.setString(3, getName(entry.getMediaType()));
                    statement.setString(4, getName(entry.getLanguage()));
                    statement.setString(5, getName(entry.getCharacterSet()));
                    statement.setString(6, getName(entry.getEncoding()));
                    statement.setTimestamp(7,
                            entry.getModificationDate() != null
                                    ? new Timestamp(entry.getModificationDate().getTime())
                                    : null);
                    statement.setString(8, entry.getTag() != null ? entry.getTag().format() : null);
                    statement.setString(9,
                            entry.getHeaders() == null ? "" : serializeHeaders(entry.getHeaders()));
                    statement.setTimestamp(10,
                            entry.getExpirationDate() != null
                                    ? new Timestamp(entry.getExpirationDate().getTime())
                                    : null);
                    statement.setTimestamp(11,
                            entry.getDocumentModificationDate() != null
                                    ? new Timestamp(entry.getDocumentModificationDate().getTime())
                                    : null);
                    statement.execute();
                } finally {
                    statement.close();
                }
            }

            // Clean out existing tags for this key

            sql = "DELETE FROM " + cacheTagsTableName + " WHERE key=?";
            statement = connection.prepareStatement(sql);
            try {
                statement.setString(1, key);
                statement.execute();
            } finally {
                statement.close();
            }

            // Add tags for this key

            String[] tags = entry.getTags();
            if ((tags != null) && (tags.length > 0)) {
                sql = "INSERT INTO " + cacheTagsTableName + " (key, tag) VALUES (?, ?)";
                statement = connection.prepareStatement(sql);
                statement.setString(1, key);
                try {
                    for (String tag : tags) {
                        statement.setString(2, tag);
                        statement.execute();
                    }
                } finally {
                    statement.close();
                }
            }
        } finally {
            connection.close();
        }
    } catch (SQLException x) {
        logger.log(Level.WARNING, "Could not store cache entry", x);
    } finally {
        lock.unlock();
    }
}