Example usage for java.sql Connection createBlob

List of usage examples for java.sql Connection createBlob

Introduction

In this page you can find the example usage for java.sql Connection createBlob.

Prototype

Blob createBlob() throws SQLException;

Source Link

Document

Constructs an object that implements the Blob interface.

Usage

From source file:EmployeeInit.java

public static void main(String[] args) throws Exception {
    Connection con;
    con = DriverManager.getConnection("jdbc:derby://localhost:1527/" + "c:\\db\\employee");

    PreparedStatement ps;/*  w  w w .j  a  va2  s .c o  m*/
    ps = con.prepareStatement("insert into employee(name,photo) " + "values(?,?)");
    ps.setString(1, "Duke");

    Blob blob = con.createBlob();
    ImageIcon ii = new ImageIcon("duke.png");

    ObjectOutputStream oos;
    oos = new ObjectOutputStream(blob.setBinaryStream(1));
    oos.writeObject(ii);
    oos.close();
    ps.setBlob(2, blob);
    ps.execute();
    blob.free();
    ps.close();
}

From source file:br.com.itfox.utils.Utils.java

public static Blob stringToBlob(String s) {
    try {/*w w w . ja  va  2  s .  c  o  m*/
        if (s != null && !s.isEmpty() && s != "") {
            Connection conn = new DBase(true).getConnection();
            Blob myBlob = conn.createBlob();
            myBlob.setBytes(1, s.getBytes());
            conn.close();
            return myBlob;
        }

    } catch (SQLException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;

}

From source file:org.xsystem.sql2.dml.DmlCommand.java

Blob setBlob(Connection con, byte[] data) throws SQLException {
    Blob myBlob = con.createBlob();
    OutputStream os = myBlob.setBinaryStream(0);
    try {//from  w w  w. j  a va2s  . c om
        IOUtils.write(data, os);
        os.flush();
        return myBlob;
    } catch (IOException ex) {
        throw new SQLException(ex);
    } finally {
        Auxilary.close(os);
    }
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testTypes() throws Exception {
    Connection conn = new MyProxy();

    try {/*from   w  ww. j ava2s  .  c  o  m*/
        try {
            conn.createBlob();
        } catch (Exception e) {

        }
        try {
            conn.createClob();
        } catch (Exception e) {

        }
        try {
            conn.createNClob();
        } catch (Exception e) {

        }
        try {
            conn.createSQLXML();
        } catch (Exception e) {

        }
        try {
            conn.createStruct("java.lang.String", new String[] { "hello"

            });
        } catch (Exception e) {
        }
        try {
            conn.createArrayOf("java.lang.String", new String[] { "hello", "world" });
        } catch (Exception e) {
        }
    } finally {
        JdbcUtil.closeQuietly(conn);
    }
}

From source file:com.orangeandbronze.jblubble.jdbc.springframework.SpringJdbcBlobstoreService.java

@Override
public BlobKey createBlob(BlobstoreWriteCallback callback, String name, String contentType)
        throws IOException, BlobstoreException {
    try {// w w  w .  j av  a 2 s .  co m
        return jdbcTemplate.execute(new ConnectionCallback<BlobKey>() {
            @Override
            public BlobKey doInConnection(Connection connection) throws SQLException, DataAccessException {
                try (PreparedStatement ps = connection.prepareStatement(getInsertSql(),
                        Statement.RETURN_GENERATED_KEYS)) {
                    ps.setString(1, name);
                    ps.setString(2, contentType);
                    Blob content = connection.createBlob();
                    try {
                        long size;
                        String md5Hash = null;
                        OutputStream out = new BufferedOutputStream(content.setBinaryStream(1L),
                                getBufferSize());
                        try {
                            CountingOutputStream countingOutputStream = new CountingOutputStream(out);
                            try {
                                MessageDigest md5;
                                try {
                                    md5 = MessageDigest.getInstance(MD5_ALGORITHM_NAME);
                                    try (DigestOutputStream digestOutputStream = new DigestOutputStream(
                                            countingOutputStream, md5)) {
                                        size = callback.writeToOutputStream(digestOutputStream);
                                        if (size == -1L) {
                                            size = countingOutputStream.getByteCount();
                                        }
                                        md5Hash = new String(encodeHex(md5.digest()));
                                    }
                                } catch (NoSuchAlgorithmException e) {
                                    throw new BlobstoreException(e);
                                }
                            } finally {
                                countingOutputStream.close();
                            }
                        } finally {
                            out.close();
                        }
                        ps.setBlob(3, content);
                        ps.setLong(4, size);
                        ps.setTimestamp(5, new java.sql.Timestamp(new java.util.Date().getTime()));
                        ps.setString(6, md5Hash);
                        int rowCount = ps.executeUpdate();
                        if (rowCount == 0) {
                            throw new BlobstoreException("Creating blob failed, no rows created.");
                        }
                        long generatedId = getGeneratedKey(ps);
                        return new BlobKey(String.valueOf(generatedId));
                    } finally {
                        content.free();
                    }
                } catch (IOException e) {
                    throw new BlobstoreException("Error when creating blob", e);
                }
            }
        });
    } catch (DataAccessException e) {
        throw new BlobstoreException(e);
    }
}

From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java

public void updateBlob(Connection connection, File blobFile) throws Exception {
    PreparedStatement prepStatement = null;

    String sql = "update orderlog set " + "   jpeg_image  = ? "
            + "     where  customer_id >= ? and item_id >= ?";

    prepStatement = connection.prepareStatement(sql);

    Blob blob = connection.createBlob();

    InputStream in = null;//from  w w w.  j a v  a  2  s.  co m
    OutputStream out = null;

    try {
        in = new BufferedInputStream(new FileInputStream(blobFile));
        out = blob.setBinaryStream(1);
        IOUtils.copy(in, out);

        int i = 1;
        prepStatement.setBlob(i++, blob);
        prepStatement.setInt(i++, 1);
        prepStatement.setInt(i++, 1);

        prepStatement.executeUpdate();

        // Close and free are important to delete temp files
        prepStatement.close();
        blob.free();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

@Override
public void delistService(TransactionContext transactionContext, CompensableArchive holder) {
    Connection connection = null;
    PreparedStatement stmt = null;
    try {/* w  w  w .  ja  v  a  2  s  .co  m*/
        connection = this.getConnection();

        StringBuilder ber = new StringBuilder();
        ber.append("update tcc_compensable set variable = ?, try_committed = ? ");
        ber.append("where application = ? and endpoint = ? and global_tx_id = ? and branch_qualifier = ?");
        stmt = connection.prepareStatement(ber.toString());

        XidImpl internalXid = holder.branchXid;

        Blob blob = connection.createBlob();
        OutputStream output = blob.setBinaryStream(1);
        Serializable variable = holder.variable;
        if (variable != null) {
            byte[] bytes = this.serializer.serialize(variable);
            output.write(bytes);
        }
        output.close();

        stmt.setBlob(1, blob);
        stmt.setBoolean(2, holder.tryCommitted);

        stmt.setString(3, this.instanceKey.getApplication());
        stmt.setString(4, this.instanceKey.getEndpoint());

        stmt.setString(5, ByteUtils.byteArrayToString(internalXid.getGlobalTransactionId()));
        if (transactionContext.isCoordinator()) {
            stmt.setString(6, TransactionLogger.NULL);
        } else {
            stmt.setString(6, ByteUtils.byteArrayToString(internalXid.getBranchQualifier()));
        }

        stmt.executeUpdate();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        closeStatement(stmt);
        this.releaseConnection(connection);
    }
}

From source file:org.kawanfw.test.api.client.InsertAndUpdateBlobTestNew.java

/**
 * Insert a blob//w  w w.ja v a 2s  .  c  o m
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public void insertLoopPrepStatement(Connection connection, int numberToInsert, File blobFile) throws Exception {

    // We can now use our Remote JDBC Connection as a regular Connection!
    connection.setAutoCommit(false);

    // We will do all our remote insert in a SQL Transaction
    try {

        String sql = "insert into orderlog values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";

        // Create a new Prepared Statement
        PreparedStatement prepStatement = null;

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + numberToInsert + " orderlog...");

        for (int customerId = 1; customerId < numberToInsert + 1; customerId++) {
            int i = 1;
            long theTime = new java.util.Date().getTime();

            // We will insert a Blob (the image of the product).
            // The transfer will be done in streaming both on the client
            // and on the Servlet Server: we can upload/download very big
            // files.

            InputStream in = null;
            OutputStream out = null;

            try {
                in = new FileInputStream(blobFile);
                Blob blob = connection.createBlob();
                out = blob.setBinaryStream(1);
                IOUtils.copy(in, out);

                prepStatement = connection.prepareStatement(sql);

                prepStatement.setInt(i++, customerId);
                prepStatement.setInt(i++, customerId);
                prepStatement.setString(i++, "Item Description No " + customerId);
                prepStatement.setBigDecimal(i++, new BigDecimal(customerId));
                prepStatement.setDate(i++, new java.sql.Date(theTime));
                prepStatement.setTimestamp(i++, new Timestamp(theTime));
                prepStatement.setBlob(i++, blob);

                SqlUtil sqlUtil = new SqlUtil(connection);
                if (sqlUtil.isIngres()) {
                    prepStatement.setInt(i++, 0);
                } else {
                    prepStatement.setBoolean(i++, false);
                }

                prepStatement.setInt(i++, customerId);

                // SystemOutHandle.display("Before executeUpdate...");
                prepStatement.executeUpdate();

                // Close and free are important to delete temp files
                prepStatement.close();
                blob.free();
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

        }

        // We do either everything in a single transaction or nothing
        connection.commit(); // Commit is propagated on Server
        MessageDisplayer.display("Remote Commit Done on AceQL Server!");
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        connection.setAutoCommit(true);
    }

}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private/* synchronized */boolean pauseLogIndex(String paxosID, LogIndex logIndex) {
    if (isClosed() /* || !isLoggingEnabled() */)
        return false;
    boolean paused = false;
    // insert works because unpause always deletes on-disk copy
    String insertCmd = "insert into " + getPTable() + " (null, false, logindex, paxos_id) values (?,?)";
    String updateCmd = "update " + (USE_CHECKPOINTS_AS_PAUSE_TABLE ? getCTable() : getPTable())
            + " set logindex=? where  paxos_id=?";

    PreparedStatement pstmt = null;
    Connection conn = null;
    synchronized (this.messageLog) {
        try {/*from   w ww.j  a  v a2s .co  m*/
            conn = this.getDefaultConn();
            // try update first; if exception, try insert
            pstmt = conn.prepareStatement(updateCmd);

            byte[] logIndexBytes = logIndex != null ? deflate(logIndex.toString().getBytes(CHARSET)) : null;
            Blob blob = conn.createBlob();
            blob.setBytes(1, logIndexBytes);
            pstmt.setBlob(1, blob);

            pstmt.setString(2, paxosID);
            try {
                pstmt.executeUpdate();
            } catch (SQLException e) {
                pstmt.close();
                // try insert
                pstmt = conn.prepareStatement(insertCmd);

                blob = conn.createBlob();
                blob.setBytes(1, logIndexBytes);
                pstmt.setBlob(1, blob);

                pstmt.setString(2, paxosID);
                pstmt.executeUpdate();
            }
            paused = true;
        } catch (SQLException | IOException sqle) {
            log.severe(this + " failed to pause logIndex for " + paxosID);
            sqle.printStackTrace();
        } finally {
            cleanup(pstmt);
            cleanup(conn);
        }
        // free up memory
        this.messageLog.uncache(paxosID);
    }
    return paused;
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

private void putCheckpointState(final String paxosID, final int version, final Set<String> group,
        final int slot, final Ballot ballot, final String state, final int acceptedGCSlot,
        final long createTime, boolean existingCP) {
    if (isClosed() || DISABLE_CHECKPOINTING)
        return;/*ww  w . j  av a2 s . c  om*/

    long t1 = System.currentTimeMillis();
    // stupid derby doesn't have an insert if not exist command
    String insertCmd = "insert into " + getCTable()
            + " (version,members,slot,ballotnum,coordinator,state,create_time, min_logfile, paxos_id) values (?,?,?,?,?,?,?,?,?)";
    String updateCmd = "update " + getCTable()
            + " set version=?,members=?, slot=?, ballotnum=?, coordinator=?, state=?, create_time=?, min_logfile=? where paxos_id=?";
    // boolean existingCP = this.existsRecord(getCTable(), paxosID);
    String cmd = existingCP ? updateCmd : insertCmd;
    PreparedStatement insertCP = null;
    Connection conn = null;
    String minLogfile = null;
    try {
        conn = this.getDefaultConn();
        insertCP = conn.prepareStatement(cmd);
        insertCP.setInt(1, version);
        insertCP.setString(2, Util.toJSONString(group));
        insertCP.setInt(3, slot);
        insertCP.setInt(4, ballot.ballotNumber);
        insertCP.setInt(5, ballot.coordinatorID);
        if (getCheckpointBlobOption()) {
            Blob blob = conn.createBlob();
            blob.setBytes(1, state.getBytes(CHARSET));
            insertCP.setBlob(6, blob);
        } else
            insertCP.setString(6, state);
        insertCP.setLong(7, createTime);
        insertCP.setString(8, minLogfile = this.getSetGCAndGetMinLogfile(paxosID, version,
                slot - acceptedGCSlot < 0 ? slot : acceptedGCSlot));
        insertCP.setString(9, paxosID);
        insertCP.executeUpdate();
        // conn.commit();
        incrTotalCheckpoints();

        DelayProfiler.updateDelay(appName + ".checkpoint", t1);
        // why can't insertCP.toString() return the query string? :/
        if (shouldLogCheckpoint())
            log.log(Level.INFO, "{0} checkpointed ({1}:{2}, {3}, <{4}, {5}>, ({6}, {7}) [{8}]) in {9} ms",
                    new Object[] { this, paxosID, version, (group), slot, ballot, acceptedGCSlot, minLogfile,
                            Util.truncate(state, TRUNCATED_STATE_SIZE, TRUNCATED_STATE_SIZE),
                            (System.currentTimeMillis() - t1), });
    } catch (SQLException | UnsupportedEncodingException sqle) {
        log.log(Level.SEVERE,
                "{0} SQLException while checkpointing using command {1} with values "
                        + " {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9} " + "; previous checkpoint state = {10}",
                new Object[] { this, cmd, version, group, slot, ballot.ballotNumber, ballot.coordinatorID,
                        state, createTime, paxosID, existingCP });
        sqle.printStackTrace();
    } finally {
        cleanup(insertCP);
        cleanup(conn);
    }

    this.deleteOutdatedMessages(paxosID, version, ballot, acceptedGCSlot, ballot.ballotNumber,
            ballot.coordinatorID, acceptedGCSlot);

}