Example usage for java.sql PreparedStatement setBinaryStream

List of usage examples for java.sql PreparedStatement setBinaryStream

Introduction

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

Prototype

void setBinaryStream(int parameterIndex, java.io.InputStream x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given input stream.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table images (Id int, b BLOB);");

    File file = new File("myimage.gif");
    FileInputStream fis = new FileInputStream(file);
    PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
    ps.setString(1, "10");
    ps.setBinaryStream(2, fis);
    ps.executeUpdate();//from  ww  w  .  j  a  v  a  2 s .  c  om

    ResultSet rset = st.executeQuery("select b from images");
    InputStream stream = rset.getBinaryStream(1);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    int a1 = stream.read();
    while (a1 >= 0) {
        output.write((char) a1);
        a1 = stream.read();
    }
    Image myImage = Toolkit.getDefaultToolkit().createImage(output.toByteArray());
    output.close();

    ps.close();

    fis.close();
    st.close();
    conn.close();
}

From source file:com.javacreed.examples.sql.Example3.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override// w ww .jav a 2 s  . c om
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(baos)) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example3.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.sql.Example4.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {

            @Override/*w w w  .j ava 2s.  c om*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (InputStream in = new LZ4BlockInputStream(
                        CryptoUtils.wrapInToCipheredInputStream(resultSet.getBinaryStream("compressed")))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new LZ4BlockOutputStream(
                        CryptoUtils.wrapInToCipheredOutputStream(baos))) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }

        };
        test.runTest();
    }
    Example4.LOGGER.debug("Done");
}

From source file:com.javacreed.examples.sql.Example2.java

public static void main(final String[] args) throws Exception {
    try (BasicDataSource dataSource = DatabaseUtils.createDataSource();
            Connection connection = dataSource.getConnection()) {
        final ExampleTest test = new ExampleTest(connection, "compressed_table", "compressed") {
            @Override/*from w w  w.j a  va2  s .  c  o  m*/
            protected String parseRow(final ResultSet resultSet) throws Exception {
                try (GZIPInputStream in = new GZIPInputStream(resultSet.getBinaryStream("compressed"))) {
                    return IOUtils.toString(in, "UTF-8");
                }
            }

            @Override
            protected void setPreparedStatement(final String data, final PreparedStatement statement)
                    throws Exception {
                // Compress the data before inserting it. We need to compress before inserting the data to make this process
                // as realistic as possible.
                final ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length());
                try (OutputStream out = new GZIPOutputStream(baos, data.length())) {
                    out.write(data.getBytes("UTF-8"));
                }
                statement.setBinaryStream(1, new ByteArrayInputStream(baos.toByteArray()));
            }
        };
        test.runTest();
    }
    Example2.LOGGER.debug("Done");
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAO.java

/**
 * Adds a record into the database with uploaded file's information
 *
 * @param dto   Uploaded File Information represented by {@link UploadedFileInfoDTO}
 * @param uploadedInputStream Input stream with the uploaded file content
 * @throws UsagePublisherException if there is an error while getting a connection or executing the query
 *//*from  w  w  w .j a v a  2s  .  c om*/
public static void persistFileUpload(UploadedFileInfoDTO dto, InputStream uploadedInputStream)
        throws UsagePublisherException {
    Connection connection = null;
    boolean autoCommitStatus = false;
    PreparedStatement statement = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        autoCommitStatus = connection.getAutoCommit();
        connection.setAutoCommit(false);
        statement = connection.prepareStatement(MicroGatewayAPIUsageConstants.INSERT_UPLOADED_FILE_INFO_QUERY);
        statement.setString(1, dto.getTenantDomain());
        statement.setString(2, dto.getFileName());
        statement.setTimestamp(3, new Timestamp(dto.getTimeStamp()));
        statement.setBinaryStream(4, uploadedInputStream);
        statement.executeUpdate();
        connection.commit();
        if (log.isDebugEnabled()) {
            log.debug("Persisted Uploaded File info : " + dto.toString());
        }
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException e1) {
            log.error("Error occurred while rolling back inserting uploaded information into db transaction,",
                    e1);
        }
        throw new UsagePublisherException("Error occurred while inserting uploaded information into database",
                e);
    } finally {
        try {
            connection.setAutoCommit(autoCommitStatus);
        } catch (SQLException e) {
            log.warn("Failed to reset auto commit state of database connection to the previous state.", e);
        }
        APIMgtDBUtil.closeAllConnections(statement, connection, null);
    }
}

From source file:test.Test_db.java

public void test() throws SQLException, ClassNotFoundException {
    String string = "vnws?";
    ByteArrayInputStream bain = new ByteArrayInputStream(string.getBytes());

    System.out.println(string.getBytes().length);
    Class.forName("org.postgresql.Driver");
    String url = "jdbc:postgresql://localhost:5432/free-choice-v1";
    String url1 = "jdbc:postgresql://localhost:5432/test";
    Connection conn = DriverManager.getConnection(url, "bcgh2013", "2013.bcgh.start");
    //      Connection conn = cpds.getConnection();
    PreparedStatement ps = conn.prepareStatement("insert into psw(bs128)values(?)");

    ps.setBinaryStream(1, bain);
    //      ps.setBytes(1, string.getBytes());
    ps.execute();//  w w  w . j  ava 2s .  com
    //      ps.setObject(1, string.getBytes(), POst)
    conn.close();
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // change the following parameters to connect to the oracle database
    String username = "patzelt";
    String password = "Chocolate1";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int photo_id;

    try {/*w w  w . j  av a 2s.  c om*/
        // Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }
        long size = item.getSize();

        // Get the image stream
        InputStream instream = item.getInputStream();

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         * First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); // good
        rset1.next();
        photo_id = rset1.getInt(1);
        /**
        // Insert an empty blob into the table first. Note that you have to
        // use the Oracle specific function empty_blob() to create an empty
        // blob
        stmt.execute("INSERT INTO pictures (photo_id, pic_des, pic) VALUES(" + photo_id + ",'test',empty_blob())");
                
        // to retrieve the lob_locator
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE photo_id = " + photo_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);
                
        **/

        stmt.execute("INSERT INTO pictures VALUES(" + photo_id + ",'test',empty_blob())");

        PreparedStatement stmt1 = conn
                .prepareStatement("UPDATE pictures SET pic = ? WHERE photo_id = + " + photo_id);
        stmt1.setBinaryStream(1, instream);
        stmt1.executeUpdate();

        /**
        // Write the image to the blob object
        OutputStream outstream = myblob.setBinaryStream(size);
        //int bufferSize = myblob.getBufferSize();
        //byte[] buffer = new byte[bufferSize];
        //int length = -1;
        //while ((length = instream.read(buffer)) != -1)
           //outstream.write(buffer, 0, length);
        outstream.write(pic);
        instream.close();
        outstream.close();
                
        //String update = "UPDATE pictures SET pic = " + myblob + " WHERE photo_id = " + photo_id;
        //stmt.execute(update);
        **/

        response_message = "YAHHOOOOOO";
        conn.close();

    } catch (Exception ex) {
        // System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    // Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:ueg.watchdog.model.ProcessedFrameStat.java

public boolean save() {
    String query = "INSERT INTO `" + TABLE
            + "` (video_id,occurred_timestamp,description,face,profile_id) VALUES(?,?,?,?,?)";
    Connection connection = DbConnect.getDBConnection();
    try {//from  ww w  .  j av  a  2s .c o  m
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setInt(1, getVideoId());
        statement.setTimestamp(2, WatchDogUtils.toMySQLDate(getTimestamp()));
        statement.setString(3, getDescription());
        statement.setBinaryStream(4, ImageUtils.toInputStream(getFace()));
        statement.setString(5, getProfileId());
        statement.execute();
        String fetchIdQuery = "SELECT `id` FROM `" + TABLE + "` ORDER BY `id`  DESC LIMIT 1";
        PreparedStatement fetchIdStatement = connection.prepareStatement(fetchIdQuery);
        ResultSet resultSet = fetchIdStatement.executeQuery();
        resultSet.first();
        this.id = resultSet.getInt("id");
    } catch (Exception e) {
        logger.error("Error occurred when saving stat to database", e);
        return false;
    } finally {
        DbUtils.closeQuietly(connection);
    }
    logger.debug("Successfully saved processed frame stats");
    return true;
}

From source file:nz.co.gregs.dbvolution.actions.DBUpdateLargeObjects.java

private void setUsingBinaryStream(DBDefinition defn, DBRow row, final String col,
        final DBLargeObject largeObject, DBDatabase db, DBStatement statement) throws SQLException {
    String sqlString = defn.beginUpdateLine() + defn.formatTableName(row) + defn.beginSetClause()
            + defn.formatColumnName(col) + defn.getEqualsComparator() + defn.getPreparedVariableSymbol()
            + defn.beginWhereClause() + defn.formatColumnName(row.getPrimaryKeyColumnName())
            + defn.getEqualsComparator() + row.getPrimaryKey().toSQLString(db) + defn.endSQLStatement();
    //               db.printSQLIfRequested(sqlString);
    log.debug(sqlString);//from w w w  .  ja v a 2 s . c  o m
    PreparedStatement prep = statement.getConnection().prepareStatement(sqlString);
    try {
        try {
            prep.setBinaryStream(1, largeObject.getInputStream());
        } catch (SQLException exp) {
            try {
                prep.setBinaryStream(1, largeObject.getInputStream(), largeObject.getSize());
            } catch (SQLException exp2) {
                throw new DBRuntimeException(exp);
            }
        }
        prep.execute();
    } finally {
        prep.close();
    }
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAOTest.java

@Test
public void getFileContent() throws Exception {
    Connection connection = APIMgtDBUtil.getConnection();
    InputStream anyInputStream = new ByteArrayInputStream("test data".getBytes());
    String insertFilesQuery = "INSERT INTO AM_USAGE_UPLOADED_FILES "
            + "(TENANT_DOMAIN,FILE_NAME,FILE_TIMESTAMP,FILE_CONTENT) VALUES(?,?,?,?);";
    PreparedStatement statement = connection.prepareStatement(insertFilesQuery);
    Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
    statement.setString(1, tenantDomain);
    statement.setString(2, fileName);// ww  w.j av  a 2 s .  c  o m
    statement.setTimestamp(3, timeStamp);
    statement.setBinaryStream(4, anyInputStream);
    statement.executeUpdate();
    connection.commit();

    UploadedFileInfoDTO uploadedFileInfoDTO = new UploadedFileInfoDTO(tenantDomain, fileName,
            timeStamp.getTime());
    InputStream returnedInputStream = UploadedUsageFileInfoDAO.getFileContent(uploadedFileInfoDTO);
    Assert.assertNotNull(returnedInputStream);

    String deleteFilesQuery = "DELETE FROM AM_USAGE_UPLOADED_FILES";
    Statement st = connection.createStatement();
    st.executeUpdate(deleteFilesQuery);
    connection.close();
}