Example usage for java.sql PreparedStatement setBlob

List of usage examples for java.sql PreparedStatement setBlob

Introduction

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

Prototype

void setBlob(int parameterIndex, InputStream inputStream) throws SQLException;

Source Link

Document

Sets the designated parameter to a InputStream object.

Usage

From source file:Package.Projectoverviewservlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    frame.setAlwaysOnTop(true);//from   www . ja  v  a 2  s . co m
    if (request.getParameter("submit") != null) {
        Database database = null;
        try {
            database = new Database();
            database.Connect();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            String contentType = request.getContentType();
            if ((contentType.indexOf("multipart/form-data") >= 0)) {
                try {
                    Part filePart = request.getPart("fileupload");
                    Image image = ImageIO.read(filePart.getInputStream());
                    String INSERT_PICTURE = "INSERT INTO \"PICTURE\"(\"PICTUREID\", \"PROJECTID\", \"HEIGHT\", \"WIDTH\", \"COLORTYPE\", \"PICTURE\") VALUES (PictureSequence.nextval, 1,"
                            + image.getHeight(null) + "," + image.getWidth(null) + ", 'Color', ?)";
                    InputStream is = null;
                    PreparedStatement ps = null;
                    try {
                        is = filePart.getInputStream();
                        ps = database.myConn.prepareStatement(INSERT_PICTURE);
                        ps.setBlob(1, is);
                        ps.executeUpdate();
                        database.myConn.commit();
                        JOptionPane.showMessageDialog(frame, "De afbeelding is succesvol geupload.");
                    } finally {
                        try {
                            ps.close();
                            is.close();
                        } catch (Exception exception) {

                        }
                    }
                } catch (IOException | ServletException | SQLException ex) {
                    System.out.println(ex);
                }
            } else {
                JOptionPane.showMessageDialog(frame, "Er is iets fout gegaan probeer het opnieuw");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame, ex.getMessage());
        }
        response.sendRedirect("projectoverview.jsp");
    }

    if (request.getParameter("deleteproject") != null) {
        String[] selectresults = request.getParameterValues("selectproject");
        po.deleteProject(Integer.parseInt(selectresults[0]));

    }

    if (request.getParameter("openproject") != null) {
        try {
            String[] selectresults = request.getParameterValues("selectproject");
            Project project = po.getProject(Integer.parseInt(selectresults[0]));
            request.setAttribute("project", project);
            request.getRequestDispatcher("projectoverview.jsp").forward(request, response);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame, ex.getMessage());
        }

    }

    if (request.getParameter("Save") != null) {

        Project project = (Project) request.getAttribute("project");
        if (project != null) {
            try {
                System.out.println(request.getParameter("startdate"));
                po.updateProject(project.getProjectID(), request.getParameter("name"),
                        request.getParameter("client"),
                        new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")),
                        new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate")));
            } catch (Exception ex) {

            }
        } else {
            String username = "";
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals("Email")) {
                    username = cookie.getValue();
                }
            }
            if (!username.isEmpty()) {
                try {
                    po.createProject(po.connection.getCompanyID(username), request.getParameter("name"),
                            request.getParameter("client"),
                            new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")),
                            new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate")));
                } catch (ParseException ex) {
                    Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            //roep create aan
        }
        request.getRequestDispatcher("projectoverview.jsp").forward(request, response);
    }

    if (request.getParameter("deleteimage") != null) {

    }

    if (request.getParameter("importimage") != null) {

    }

    if (request.getParameter("koppel") != null) {

    }

    if (request.getParameter("addemail") != null) {

    }

    if (request.getParameter("deleteemail") != null) {

    }

    if (request.getParameter("importemail") != null) {

    }

}

From source file:org.ambraproject.hibernate.OTMBlobType.java

public void nullSafeSet(PreparedStatement statement, java.lang.Object value, int index)
        throws HibernateException, SQLException {
    if (value == null) {
        statement.setNull(index, Types.BLOB);
    } else {/*from w  ww  .  ja v  a 2  s.co m*/
        if (value instanceof org.topazproject.otm.Blob) {
            //TODO: I don't think the following line works
            statement.setBlob(index, ((org.topazproject.otm.Blob) value).getInputStream());
        } else {
            throw new HibernateException("Object not of correct type: " + value.getClass().getName());
        }
    }

}

From source file:org.apache.jackrabbit.core.util.db.Oracle10R1ConnectionHelper.java

/**
 * Wraps any input-stream parameters in temporary blobs and frees these again after the statement
 * has been executed.//w  w w .  j ava 2 s  .  c  o m
 * 
 * {@inheritDoc}
 */
@Override
protected PreparedStatement execute(PreparedStatement stmt, Object[] params) throws SQLException {
    List<Blob> tmpBlobs = new ArrayList<Blob>();
    try {
        for (int i = 0; params != null && i < params.length; i++) {
            Object p = params[i];
            if (p instanceof StreamWrapper) {
                StreamWrapper wrapper = (StreamWrapper) p;
                Blob tmp = createTemporaryBlob(stmt.getConnection(), wrapper.getStream());
                tmpBlobs.add(tmp);
                stmt.setBlob(i + 1, tmp);
            } else if (p instanceof InputStream) {
                Blob tmp = createTemporaryBlob(stmt.getConnection(), (InputStream) p);
                tmpBlobs.add(tmp);
                stmt.setBlob(i + 1, tmp);
            } else {
                stmt.setObject(i + 1, p);
            }
        }
        stmt.execute();
        return stmt;
    } catch (Exception e) {
        throw new SQLException(e.getMessage());
    } finally {
        for (Blob blob : tmpBlobs) {
            try {
                freeTemporaryBlob(blob);
            } catch (Exception e) {
                log.warn("Could not close temporary blob", e);
            }
        }
    }
}

From source file:org.xenei.bloomgraph.bloom.sql.MySQLCommands.java

@Override
public int tripleCount(final Connection connection, final int pageId, final TripleBloomFilter filter)
        throws SQLException, IOException {
    final String sql = String.format(
            "SELECT count(*) FROM Page_%%s page WHERE hamming>=? AND log>=? AND bloommatch( ?, page.bloom)",
            pageId);//from www .j  a  v a  2s .  c o m
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        stmt = connection.prepareStatement(sql);
        stmt.setInt(1, filter.getHammingWeight());
        stmt.setDouble(2, filter.getApproximateLog(APPROX_LOG_DEPTH));
        stmt.setBlob(3, DBIO.asInputStream(filter.getByteBuffer()));
        rs = stmt.executeQuery();
        if (rs.next()) {
            return rs.getInt(1);
        } else {
            throw new IOException("No result returned from count call");
        }
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
    }
}

From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java

@Test
public void testBlob() throws Exception {
    UUID blobId = UUID.randomUUID();
    CassandraBlob blobValue = new CassandraBlob(RandomStringUtils.random(10));
    String insert = "INSERT INTO " + TYPETABLE + " (id,blobValue,dataMapValue) " + " VALUES("
            + blobId.toString() + ", ?, {'12345': bigintAsBlob(12345)});";

    PreparedStatement statement = con.prepareStatement(insert);
    statement.setBlob(1, blobValue);

    statement.executeUpdate();/*from   www  .j av  a  2  s.c  o  m*/
    statement.close();

    Statement select1 = con.createStatement();
    String query = "SELECT blobValue FROM " + TYPETABLE + " WHERE id=" + blobId.toString() + ";";
    ResultSet result = select1.executeQuery(query);
    result.next();

    Blob blobResult = result.getBlob(1);
    assertEquals(blobValue, blobResult);

    Statement select2 = con.createStatement();
    String query2 = "SELECT dataMapValue FROM " + TYPETABLE + " WHERE id=" + blobId.toString() + ";";
    ResultSet result2 = select2.executeQuery(query2);
    result2.next();

    Object mapResult = result2.getObject(1);

    assertTrue(mapResult instanceof Map);
    assertEquals("There should be 1 record in the map", 1, ((Map) mapResult).size());
    assertNotNull("Entry for '12345' should be in the map", ((Map) mapResult).get("12345"));
    assertNull("Entry for '54321' should NOT be in the map", ((Map) mapResult).get("54321"));

}

From source file:org.springframework.jdbc.support.lob.TemporaryLobCreator.java

@Override
public void setBlobAsBinaryStream(PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream,
        int contentLength) throws SQLException {

    if (binaryStream != null) {
        Blob blob = ps.getConnection().createBlob();
        try {//  w  w  w.  ja  v a2  s .  c  om
            FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
        } catch (IOException ex) {
            throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
        }
        this.temporaryBlobs.add(blob);
        ps.setBlob(paramIndex, blob);
    } else {
        ps.setBlob(paramIndex, (Blob) null);
    }

    if (logger.isDebugEnabled()) {
        logger.debug(
                binaryStream != null ? "Copied binary stream into temporary BLOB with length " + contentLength
                        : "Set BLOB to null");
    }
}

From source file:org.xenei.bloomgraph.bloom.sql.MySQLCommands.java

@Override
public PreparedStatement pageIndexSearch(final Connection connection, final PageBloomFilter filter)
        throws SQLException {
    PreparedStatement stmt = null;
    try {/*ww  w.j a v  a2 s . co  m*/
        stmt = connection.prepareStatement(
                "SELECT bloom, idx FROM PageIndex WHERE hamming>=? AND log>=? AND bloommatch( ?, PageIndex.bloom )");
        stmt.setInt(1, filter.getHammingWeight());
        stmt.setDouble(2, filter.getApproximateLog(0));
        stmt.setBlob(3, DBIO.asInputStream(filter.getByteBuffer()));
        return stmt;
    } catch (final SQLException e) {
        DbUtils.closeQuietly(stmt);
        throw e;
    }
}

From source file:org.hsweb.ezorm.rdb.executor.AbstractJdbcSqlExecutor.java

/**
 * ?//w  ww  .  j a  va2  s  . c o  m
 *
 * @param statement
 * @param info
 * @throws Exception
 */
protected void preparedParam(PreparedStatement statement, SQLInfo info) throws SQLException {
    int index = 1;
    //?
    for (Object object : info.getParam()) {
        if (object instanceof Date)
            statement.setTimestamp(index++, new java.sql.Timestamp(((Date) object).getTime()));
        else if (object instanceof byte[]) {
            statement.setBlob(index++, new ByteArrayInputStream((byte[]) object));
        } else
            statement.setObject(index++, object);
    }
}

From source file:com.amazon.carbonado.repo.jdbc.OracleSupportStrategy.java

/**
 * @return original blob if too large and post-insert update is required, null otherwise
 * @throws PersistException instead of FetchException since this code is
 * called during an insert operation//from w w  w  .  j av  a 2s .c  om
 */
@Override
com.amazon.carbonado.lob.Blob setBlobValue(PreparedStatement ps, int column, com.amazon.carbonado.lob.Blob blob)
        throws PersistException {
    try {
        long length = blob.getLength();
        if (length > BLOB_CHUNK_LIMIT || ((long) ((int) length)) != length) {
            if (mBLOB_empty_lob == null) {
                return super.setBlobValue(ps, column, blob);
            }

            try {
                ps.setBlob(column, (java.sql.Blob) mBLOB_empty_lob.invoke(null));
                return blob;
            } catch (InvocationTargetException e) {
                throw mRepo.toPersistException(e.getCause());
            } catch (Exception e) {
                throw mRepo.toPersistException(e);
            }
        }

        if (blob instanceof OracleBlob) {
            ps.setBlob(column, ((OracleBlob) blob).getInternalBlobForPersist());
            return null;
        }

        ps.setBinaryStream(column, blob.openInputStream(), (int) length);
        return null;
    } catch (SQLException e) {
        throw mRepo.toPersistException(e);
    } catch (FetchException e) {
        throw e.toPersistException();
    }
}

From source file:org.wso2.carbon.event.processor.core.internal.persistence.DBPersistenceStore.java

public void saveRevision(String executionPlanId, String revision, byte[] snapshot) {

    PreparedStatement stmt = null;
    Connection con = null;//w w w .ja  v a  2s .co m
    try {
        try {
            con = dataSource.getConnection();
            con.setAutoCommit(false);
        } catch (SQLException e) {
            log.error("Cannot establish connection to the data source" + dataSourceName, e);
        }
        stmt = con.prepareStatement(executionInfo.getPreparedInsertStatement());
        stmt.setString(1, getTenantId());
        stmt.setString(2, executionPlanId);
        stmt.setString(3, revision);
        stmt.setBlob(4, new SerialBlob(snapshot));
        stmt.executeUpdate();
        con.commit();
    } catch (SQLException e) {
        log.error("Error while saving revision" + revision + " of the execution plan" + executionPlanId
                + "to the database", e);
    } finally {
        cleanupConnections(stmt, con);
    }
}