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.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * Sets the value of this blob as the specified bytes.
 * /*  ww w . ja v  a2 s. c o m*/
 * @param table
 * @param columnName
 * @param id
 * @param bytes
 * @return The number of bytes written.
 */
public int setBlobAsBytes(String table, String columnName, String id, byte[] bytes) {
    Connection conn = Database.getConnection();
    int written = 0;
    PreparedStatement prepared = null;
    try {
        // get the blob
        String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN
                + " = '" + id + "'";
        prepared = conn.prepareStatement(update);
        prepared.setBytes(1, bytes);
        prepared.executeUpdate();
        written = bytes.length;
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (prepared != null)
                prepared.close();
            this.closeConnection(conn);
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }

    return written;
}

From source file:com.alfaariss.oa.engine.session.jdbc.JDBCSessionFactory.java

/**
 * Uses a batch update to persist all supplied sessions.
 * @param sessions The sessions to persist.
 * @throws PersistenceException If persistance fails.
 * /*from ww  w . j a v  a2s  . c  o m*/
 * @see IEntityManager#persist(IEntity[])
 * @see PreparedStatement#addBatch()
 */
public void persist(JDBCSession[] sessions) throws PersistenceException {
    if (sessions == null)
        throw new IllegalArgumentException("Suplied session array is empty or invalid");

    Connection connection = null;
    PreparedStatement psInsert = null;
    PreparedStatement psDelete = null;
    PreparedStatement psUpdate = null;
    try {
        connection = _oDataSource.getConnection(); //Manage connection
        connection.setAutoCommit(false);

        psInsert = connection.prepareStatement(_sInsertQuery);
        psDelete = connection.prepareStatement(_sRemoveQuery);
        psUpdate = connection.prepareStatement(_sUpdateQuery);

        for (JDBCSession session : sessions) {
            String id = session.getId();
            if (id == null) {
                byte[] baId = new byte[ISession.ID_BYTE_LENGTH];
                do {
                    _random.nextBytes(baId);
                    try {
                        id = ModifiedBase64.encode(baId);
                    } catch (UnsupportedEncodingException e) {
                        _logger.error("Could not create id for byte[]: " + baId, e);
                        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
                    }
                } while (exists(id)); //Key allready exists   

                session.setId(id);
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                session.setTgtExpTime(expiration);
                psInsert.setString(1, id);
                psInsert.setString(2, session.getTGTId());
                psInsert.setInt(3, session.getState().ordinal());
                psInsert.setString(4, session.getRequestorId());
                psInsert.setString(5, session.getProfileURL());
                psInsert.setBytes(6, Serialize.encode(session.getUser()));
                psInsert.setTimestamp(7, new Timestamp(expiration));
                psInsert.setBoolean(8, session.isForcedAuthentication());
                psInsert.setBoolean(9, session.isPassive());
                psInsert.setBytes(10, Serialize.encode(session.getAttributes()));
                psInsert.setString(11, session.getForcedUserID());
                psInsert.setBytes(12, Serialize.encode(session.getLocale()));
                psInsert.setBytes(13, Serialize.encode(session.getSelectedAuthNProfile()));
                psInsert.setBytes(14, Serialize.encode(session.getAuthNProfiles()));
                psInsert.addBatch();
            } else if (session.isExpired()) //Expired
            {
                _logger.info("Session Expired: " + id);

                _eventLogger.info(new UserEventLogItem(session, null, UserEvent.SESSION_EXPIRED, this, null));

                psDelete.setString(1, id);
                psDelete.addBatch();
            } else //Update
            {
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                session.setTgtExpTime(expiration);
                psUpdate.setString(1, session.getTGTId());
                psUpdate.setInt(2, session.getState().ordinal());
                psUpdate.setString(3, session.getRequestorId());
                psUpdate.setString(4, session.getProfileURL());
                psUpdate.setBytes(5, Serialize.encode(session.getUser()));
                psUpdate.setTimestamp(6, new Timestamp(expiration));
                psUpdate.setBoolean(7, session.isForcedAuthentication());
                psInsert.setBoolean(8, session.isPassive());
                psUpdate.setBytes(9, Serialize.encode(session.getAttributes()));
                psUpdate.setString(10, session.getForcedUserID());
                psUpdate.setBytes(11, Serialize.encode(session.getLocale()));
                psUpdate.setBytes(12, Serialize.encode(session.getSelectedAuthNProfile()));
                psUpdate.setBytes(13, Serialize.encode(session.getAuthNProfiles()));
                psUpdate.setString(14, id);
                psUpdate.addBatch();
            }
        }
        try {
            int[] iResult = psInsert.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalAdded = 0;
                for (int i : iResult)
                    iTotalAdded += i;

                _logger.info(iTotalAdded + " new session(s) added by batch");
            }
        } catch (SQLException e) {
            _logger.error("Could not execute insert batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT);
        }
        try {
            int[] iResult = psDelete.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalDeleted = 0;
                for (int i : iResult)
                    iTotalDeleted += i;

                _logger.info(iTotalDeleted + " session(s) deleted by batch");
            }

        } catch (SQLException e) {
            _logger.error("Could not execute delete batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
        }
        try {
            int[] iResult = psUpdate.executeBatch();
            if (_logger.isDebugEnabled()) {
                int iTotalUpdated = 0;
                for (int i : iResult)
                    iTotalUpdated += i;

                _logger.info(iTotalUpdated + " session(s) updated by batch");
            }
        } catch (SQLException e) {
            _logger.error("Could not execute update batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE);
        }

        connection.commit();
    } catch (SQLException e) {
        _logger.error("Could not execute batch", e);
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }

        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
    } catch (PersistenceException e) {
        try {
            if (connection != null)
                connection.rollback();
        } catch (SQLException e1) {
            _logger.warn("Could not rollback batch", e);
        }
        throw e;
    } catch (Exception e) {
        _logger.error("Internal error during session persist", e);
        throw new PersistenceException(SystemErrors.ERROR_RESOURCE_CONNECT);
    } finally {
        try {
            if (psInsert != null)
                psInsert.close();
        } catch (SQLException e) {
            _logger.debug("Could not close insert statement", e);
        }
        try {
            if (psDelete != null)
                psDelete.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete statement", e);
        }
        try {
            if (psUpdate != null)
                psUpdate.close();
        } catch (SQLException e) {
            _logger.debug("Could not close update statement", e);
        }
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            _logger.debug("Could not close connection", e);
        }
    }
}

From source file:net.pms.dlna.DLNAMediaDatabase.java

public synchronized void insertData(String name, long modified, int type, DLNAMediaInfo media) {
    Connection conn = null;/* ww w  .j  a  va  2 s  . co  m*/
    PreparedStatement ps = null;
    try {
        conn = getConnection();
        ps = conn.prepareStatement(
                "INSERT INTO FILES(FILENAME, MODIFIED, TYPE, DURATION, BITRATE, WIDTH, HEIGHT, SIZE, CODECV, FRAMERATE, ASPECT, ASPECTRATIOCONTAINER, ASPECTRATIOVIDEOTRACK, REFRAMES, AVCLEVEL, BITSPERPIXEL, THUMB, CONTAINER, MODEL, EXPOSURE, ORIENTATION, ISO, MUXINGMODE, FRAMERATEMODE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        ps.setString(1, name);
        ps.setTimestamp(2, new Timestamp(modified));
        ps.setInt(3, type);
        if (media != null) {
            if (media.getDuration() != null) {
                ps.setDouble(4, media.getDurationInSeconds());
            } else {
                ps.setNull(4, Types.DOUBLE);
            }

            int databaseBitrate = 0;
            if (type != Format.IMAGE) {
                databaseBitrate = media.getBitrate();
                if (databaseBitrate == 0) {
                    logger.debug("Could not parse the bitrate from: " + name);
                }
            }
            ps.setInt(5, databaseBitrate);

            ps.setInt(6, media.getWidth());
            ps.setInt(7, media.getHeight());
            ps.setLong(8, media.getSize());
            ps.setString(9, left(media.getCodecV(), SIZE_CODECV));
            ps.setString(10, left(media.getFrameRate(), SIZE_FRAMERATE));
            ps.setString(11, left(media.getAspect(), SIZE_ASPECT));
            ps.setString(12, left(media.getAspect(), SIZE_ASPECTRATIO_CONTAINER));
            ps.setString(13, left(media.getAspect(), SIZE_ASPECTRATIO_VIDEOTRACK));
            ps.setByte(14, media.getReferenceFrameCount());
            ps.setString(15, left(media.getAvcLevel(), SIZE_AVC_LEVEL));
            ps.setInt(16, media.getBitsPerPixel());
            ps.setBytes(17, media.getThumb());
            ps.setString(18, left(media.getContainer(), SIZE_CONTAINER));
            if (media.getExtras() != null) {
                ps.setString(19, left(media.getExtrasAsString(), SIZE_MODEL));
            } else {
                ps.setString(19, left(media.getModel(), SIZE_MODEL));
            }
            ps.setInt(20, media.getExposure());
            ps.setInt(21, media.getOrientation());
            ps.setInt(22, media.getIso());
            ps.setString(23, left(media.getMuxingModeAudio(), SIZE_MUXINGMODE));
            ps.setString(24, left(media.getFrameRateMode(), SIZE_FRAMERATE_MODE));
        } else {
            ps.setString(4, null);
            ps.setInt(5, 0);
            ps.setInt(6, 0);
            ps.setInt(7, 0);
            ps.setLong(8, 0);
            ps.setString(9, null);
            ps.setString(10, null);
            ps.setString(11, null);
            ps.setString(12, null);
            ps.setString(13, null);
            ps.setByte(14, (byte) -1);
            ps.setString(15, null);
            ps.setInt(16, 0);
            ps.setBytes(17, null);
            ps.setString(18, null);
            ps.setString(19, null);
            ps.setInt(20, 0);
            ps.setInt(21, 0);
            ps.setInt(22, 0);
            ps.setString(23, null);
            ps.setString(24, null);
        }
        ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        int id = -1;
        while (rs.next()) {
            id = rs.getInt(1);
        }
        rs.close();
        if (media != null && id > -1) {
            PreparedStatement insert = null;
            if (media.getAudioTracksList().size() > 0) {
                insert = conn.prepareStatement(
                        "INSERT INTO AUDIOTRACKS VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            }

            for (DLNAMediaAudio audio : media.getAudioTracksList()) {
                insert.clearParameters();
                insert.setInt(1, id);
                insert.setInt(2, audio.getId());
                insert.setString(3, left(audio.getLang(), SIZE_LANG));
                insert.setString(4, left(audio.getFlavor(), SIZE_FLAVOR));
                insert.setInt(5, audio.getAudioProperties().getNumberOfChannels());
                insert.setString(6, left(audio.getSampleFrequency(), SIZE_SAMPLEFREQ));
                insert.setString(7, left(audio.getCodecA(), SIZE_CODECA));
                insert.setInt(8, audio.getBitsperSample());
                insert.setString(9, left(trimToEmpty(audio.getAlbum()), SIZE_ALBUM));
                insert.setString(10, left(trimToEmpty(audio.getArtist()), SIZE_ARTIST));
                insert.setString(11, left(trimToEmpty(audio.getSongname()), SIZE_SONGNAME));
                insert.setString(12, left(trimToEmpty(audio.getGenre()), SIZE_GENRE));
                insert.setInt(13, audio.getYear());
                insert.setInt(14, audio.getTrack());
                insert.setInt(15, audio.getAudioProperties().getAudioDelay());
                insert.setString(16, left(trimToEmpty(audio.getMuxingModeAudio()), SIZE_MUXINGMODE));
                insert.setInt(17, audio.getBitRate());

                try {
                    insert.executeUpdate();
                } catch (JdbcSQLException e) {
                    if (e.getErrorCode() == 23505) {
                        logger.debug(
                                "A duplicate key error occurred while trying to store the following file's audio information in the database: "
                                        + name);
                    } else {
                        logger.debug(
                                "An error occurred while trying to store the following file's audio information in the database: "
                                        + name);
                    }
                    logger.debug("The error given by jdbc was: " + e);
                }
            }

            if (media.getSubtitleTracksList().size() > 0) {
                insert = conn.prepareStatement("INSERT INTO SUBTRACKS VALUES (?, ?, ?, ?, ?)");
            }
            for (DLNAMediaSubtitle sub : media.getSubtitleTracksList()) {
                if (sub.getExternalFile() == null) { // no save of external subtitles
                    insert.clearParameters();
                    insert.setInt(1, id);
                    insert.setInt(2, sub.getId());
                    insert.setString(3, left(sub.getLang(), SIZE_LANG));
                    insert.setString(4, left(sub.getFlavor(), SIZE_FLAVOR));
                    insert.setInt(5, sub.getType().getStableIndex());
                    try {
                        insert.executeUpdate();
                    } catch (JdbcSQLException e) {
                        if (e.getErrorCode() == 23505) {
                            logger.debug(
                                    "A duplicate key error occurred while trying to store the following file's subtitle information in the database: "
                                            + name);
                        } else {
                            logger.debug(
                                    "An error occurred while trying to store the following file's subtitle information in the database: "
                                            + name);
                        }
                        logger.debug("The error given by jdbc was: " + e);
                    }
                }
            }
            close(insert);
        }
    } catch (SQLException se) {
        if (se.getErrorCode() == 23001) {
            logger.debug("Duplicate key while inserting this entry: " + name + " into the database: "
                    + se.getMessage());
        } else {
            logger.error(null, se);
        }
    } finally {
        close(ps);
        close(conn);
    }
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * This is a special method used to update the baseClass attribute of MdType
 * and it is used only within the TransactionManagement aspect, hence it takes
 * a JDBC connection object as a parameter.
 * /*from www.  j  a va  2  s . c o  m*/
 * @param mdTypeId
 * @param table
 * @param classColumnName
 * @param classBytes
 * @param sourceColumnName
 * @param source
 * @param conn
 */
@Override
public int updateClassAndSource(String mdTypeId, String table, String classColumnName, byte[] classBytes,
        String sourceColumnName, String source, Connection conn) {
    PreparedStatement prepared = null;

    int written = 0;

    try {
        // clear the blob
        this.truncateBlob(table, classColumnName, mdTypeId, 0, conn);

        // get the blob
        String update = "UPDATE " + table + " SET " + classColumnName + " = ?, " + sourceColumnName
                + " = ? WHERE " + EntityDAOIF.ID_COLUMN + " = '" + mdTypeId + "'";
        prepared = conn.prepareStatement(update);
        prepared.setBytes(1, classBytes);
        prepared.setString(2, source);

        prepared.executeUpdate();

        written = classBytes.length;
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (prepared != null)
                prepared.close();
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return written;
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * This is the core method to set the parameter of a prepared statement to a given value.
 * The primary purpose of this method is to call the appropriate method on the statement,
 * and to give database-specific implementations the ability to change this behavior.
 * //from  www .j  ava 2 s .  c o m
 * @param statement The statement
 * @param sqlIndex  The parameter index
 * @param typeCode  The JDBC type code
 * @param value     The value
 * @throws SQLException If an error occurred while setting the parameter value
 */
protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value)
        throws SQLException {
    if (value == null) {
        statement.setNull(sqlIndex, typeCode);
    } else if (value instanceof String) {
        statement.setString(sqlIndex, (String) value);
    } else if (value instanceof byte[]) {
        statement.setBytes(sqlIndex, (byte[]) value);
    } else if (value instanceof Boolean) {
        statement.setBoolean(sqlIndex, ((Boolean) value).booleanValue());
    } else if (value instanceof Byte) {
        statement.setByte(sqlIndex, ((Byte) value).byteValue());
    } else if (value instanceof Short) {
        statement.setShort(sqlIndex, ((Short) value).shortValue());
    } else if (value instanceof Integer) {
        statement.setInt(sqlIndex, ((Integer) value).intValue());
    } else if (value instanceof Long) {
        statement.setLong(sqlIndex, ((Long) value).longValue());
    } else if (value instanceof BigDecimal) {
        // setObject assumes a scale of 0, so we rather use the typed setter
        statement.setBigDecimal(sqlIndex, (BigDecimal) value);
    } else if (value instanceof Float) {
        statement.setFloat(sqlIndex, ((Float) value).floatValue());
    } else if (value instanceof Double) {
        statement.setDouble(sqlIndex, ((Double) value).doubleValue());
    } else {
        statement.setObject(sqlIndex, value, typeCode);
    }
}

From source file:helma.objectmodel.db.NodeManager.java

private void setStatementValue(PreparedStatement stmt, int stmtNumber, Property p, int columnType)
        throws SQLException {
    if (p.getValue() == null) {
        stmt.setNull(stmtNumber, columnType);
    } else {/*  w  w w  . java2 s . c  om*/
        switch (columnType) {
        case Types.BIT:
        case Types.BOOLEAN:
            stmt.setBoolean(stmtNumber, p.getBooleanValue());

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            stmt.setLong(stmtNumber, p.getIntegerValue());

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
        case Types.NUMERIC:
        case Types.DECIMAL:
            stmt.setDouble(stmtNumber, p.getFloatValue());

            break;

        case Types.LONGVARBINARY:
        case Types.VARBINARY:
        case Types.BINARY:
        case Types.BLOB:
            Object b = p.getJavaObjectValue();
            if (b instanceof byte[]) {
                byte[] buf = (byte[]) b;
                try {
                    stmt.setBytes(stmtNumber, buf);
                } catch (SQLException x) {
                    ByteArrayInputStream bout = new ByteArrayInputStream(buf);
                    stmt.setBinaryStream(stmtNumber, bout, buf.length);
                }
            } else {
                throw new SQLException(
                        "expected byte[] for binary column '" + p.getName() + "', found " + b.getClass());
            }

            break;

        case Types.LONGVARCHAR:
            try {
                stmt.setString(stmtNumber, p.getStringValue());
            } catch (SQLException x) {
                String str = p.getStringValue();
                Reader r = new StringReader(str);
                stmt.setCharacterStream(stmtNumber, r, str.length());
            }

            break;

        case Types.CLOB:
            String val = p.getStringValue();
            Reader isr = new StringReader(val);
            stmt.setCharacterStream(stmtNumber, isr, val.length());

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            stmt.setString(stmtNumber, p.getStringValue());

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            stmt.setTimestamp(stmtNumber, p.getTimestampValue());

            break;

        case Types.NULL:
            stmt.setNull(stmtNumber, 0);

            break;

        default:
            stmt.setString(stmtNumber, p.getStringValue());

            break;
        }
    }
}

From source file:com.runwaysdk.dataaccess.database.general.Oracle.java

/**
 * Sets the value of this blob as the specified bytes.
 *
 * @param table//from   w ww  .j  av a  2s .  co m
 * @param columnName
 * @param id
 * @param bytes
 * @return The number of bytes written.
 */
public int setBlobAsBytes(String table, String columnName, String id, byte[] bytes) {
    Connection conn = Database.getConnection();
    PreparedStatement prepared = null;
    Statement statement = null;
    ResultSet resultSet = null;
    int written = 0;
    try {
        // get the blob
        statement = conn.createStatement();
        String select = "SELECT " + columnName + " FROM " + table + " WHERE " + EntityDAOIF.ID_COLUMN + " = '"
                + id + "' FOR UPDATE";
        String update = "UPDATE " + table + " SET " + columnName + " = " + "? WHERE " + EntityDAOIF.ID_COLUMN
                + " = '" + id + "'";
        resultSet = statement.executeQuery(select);
        boolean resultSetFound = resultSet.next();
        if (!resultSetFound) {
            return 0;
        }

        Blob blob = resultSet.getBlob(columnName);

        // null check
        if (blob == null) {
            // add the bytes directly
            prepared = conn.prepareStatement(update);
            prepared.setBytes(1, bytes);
            prepared.executeUpdate();
            written = bytes.length;
        } else {
            // modify the blob
            written = blob.setBytes(1, bytes);
            if (conn.getMetaData().locatorsUpdateCopy()) {
                // The current database needs to be manually updated (it doesn't
                // support auto blob updates)
                prepared = conn.prepareStatement(update);
                prepared.setBlob(1, blob);
                prepared.executeUpdate();
            }
        }
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            if (prepared != null)
                prepared.close();
            this.closeConnection(conn);
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return written;
}

From source file:com.runwaysdk.dataaccess.database.general.PostgreSQL.java

/**
 * This is a special method used to update the generated server, common, and
 * client classes for an MdType. This method is used only within the
 * TransactionManagement aspect, hence it takes a JDBC connection object as a
 * parameter. It is up to the client to close the connection object.
 * /*from   www. j  av a 2  s  .co  m*/
 * @param table
 * @param updateTable
 * @param serverClassesColumnName
 * @param serverClassesBytes
 * @param commonClassesColumnName
 * @param commonClassesBytes
 * @param clientClassesColumnName
 * @param clientClassesBytes
 * @param conn
 */
public int updateMdFacadeGeneratedClasses(String mdFacadeId, String table, String serverClassesColumnName,
        byte[] serverClassesBytes, String commonClassesColumnName, byte[] commonClassesBytes,
        String clientClassesColumnName, byte[] clientClassesBytes, Connection conn) {
    PreparedStatement prepared = null;

    int written = 0;

    try {
        // clear the blob
        this.truncateBlob(table, serverClassesColumnName, mdFacadeId, 0, conn);
        this.truncateBlob(table, commonClassesColumnName, mdFacadeId, 0, conn);
        this.truncateBlob(table, clientClassesColumnName, mdFacadeId, 0, conn);

        // get the blob
        String update = "UPDATE " + table + " SET " + serverClassesColumnName + " = ?, "
                + commonClassesColumnName + " = ?, " + clientClassesColumnName + " = ? " + " WHERE "
                + EntityDAOIF.ID_COLUMN + " = '" + mdFacadeId + "'";
        prepared = conn.prepareStatement(update);
        prepared.setBytes(1, serverClassesBytes);
        prepared.setBytes(2, commonClassesBytes);
        prepared.setBytes(3, clientClassesBytes);
        prepared.executeUpdate();

        written += serverClassesBytes.length;
        written += commonClassesBytes.length;
        written += clientClassesBytes.length;
    } catch (SQLException e) {
        this.throwDatabaseException(e);
    } finally {
        try {
            if (prepared != null)
                prepared.close();
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
    return written;
}

From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfAbsractDataWriter.java

protected boolean processBinary(File dataFile, String tableName, String columnName, String value,
        PreparedStatement ps, int bindCount, Map<String, DfColumnMeta> columnInfoMap) throws SQLException {
    if (value == null) {
        return false; // basically no way
    }//  w w w .  j  a  v a2 s.c  o  m
    final DfColumnMeta columnInfo = columnInfoMap.get(columnName);
    if (columnInfo != null) {
        final Class<?> columnType = getBindType(tableName, columnInfo);
        if (columnType != null) {
            if (!byte[].class.isAssignableFrom(columnType)) {
                return false;
            }
            // the value should be a path to a binary file
            // from data file's current directory
            final String path;
            final String trimmedValue = value.trim();
            if (trimmedValue.startsWith("/")) { // means absolute path
                path = trimmedValue;
            } else {
                final String dataFilePath = Srl.replace(dataFile.getAbsolutePath(), "\\", "/");
                final String baseDirPath = Srl.substringLastFront(dataFilePath, "/");
                path = baseDirPath + "/" + trimmedValue;
            }
            final File binaryFile = new File(path);
            if (!binaryFile.exists()) {
                throwLoadDataBinaryFileNotFoundException(tableName, columnName, path);
            }
            final List<Byte> byteList = new ArrayList<Byte>();
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(binaryFile));
                for (int availableSize; (availableSize = bis.available()) > 0;) {
                    final byte[] bytes = new byte[availableSize];
                    bis.read(bytes);
                    for (byte b : bytes) {
                        byteList.add(b);
                    }
                }
                byte[] bytes = new byte[byteList.size()];
                for (int i = 0; i < byteList.size(); i++) {
                    bytes[i] = byteList.get(i);
                }
                ps.setBytes(bindCount, bytes);
            } catch (IOException e) {
                throwLoadDataBinaryFileReadFailureException(tableName, columnName, path, e);
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException ignored) {
                    }
                }
            }
            return true;
        }
    }
    // unsupported when meta data is not found
    return false;
}

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

/**
 * @see org.opencms.db.I_CmsProjectDriver#writePublishReport(org.opencms.db.CmsDbContext, org.opencms.util.CmsUUID, byte[])
 *//* w  w  w  . j  a va  2 s.co  m*/
public void writePublishReport(CmsDbContext dbc, CmsUUID publishId, byte[] content)
        throws CmsDataAccessException {

    Connection conn = null;
    PreparedStatement stmt = null;

    try {
        conn = m_sqlManager.getConnection(dbc);
        stmt = m_sqlManager.getPreparedStatement(conn, "C_PUBLISHJOB_WRITE_REPORT");

        if (content.length < 2000) {
            stmt.setBytes(1, content);
        } else {
            stmt.setBinaryStream(1, new ByteArrayInputStream(content), content.length);
        }

        stmt.setString(2, publishId.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);
    }
}