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.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private String saveChartToDB(JFreeChart chart, byte format, int width, int height, ChartRenderingInfo info)
        throws IOException, cfmRunTimeException {
    // Come up with a session name for the chart that is unique for the DB
    String name = "cfchart-" + com.nary.util.UUID.generateKey();

    // Generate the chart and save the contents in the name variable
    byte[] chartBytes = generateChart(chart, format, width, height, info);

    Connection con = null;/*from w ww  .  ja  v a 2  s . c  o  m*/
    java.sql.PreparedStatement Statmt = null;
    try {
        con = storageDataSource.getConnection();
        Statmt = con.prepareStatement(SQL_INSERT);
        Statmt.setString(1, name);
        Statmt.setBytes(2, chartBytes);
        Statmt.executeUpdate();
    } catch (SQLException E) {
        cfEngine.log("Error inserting data into BDCHARTDATA table: " + E);
        cfCatchData catchData = new cfCatchData();
        catchData.setType(cfCatchData.TYPE_APPLICATION);
        catchData.setDetail("Database error: " + E.getMessage());
        catchData.setMessage("Error occurred when attempting to insert data into the BDCHARTDATA table");
        throw new cfmRunTimeException(catchData);
    } finally {
        if (Statmt != null)
            try {
                Statmt.close();
            } catch (SQLException e) {
            }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException ignore) {
            }
        }
    }

    // Check if charts are being cached
    if (storageCacheSize > 0) {
        synchronized (storageCache) {
            // If we've reached the cache limit then delete the oldest cached chart.
            if (storageCache.size() == storageCacheSize) {
                String oldestChart = storageCache.remove(0);
                con = null;
                Statmt = null;
                try {
                    con = cfCHART.getStorageDataSource().getConnection();
                    Statmt = con.prepareStatement(cfCHART.SQL_DELETE);
                    Statmt.setString(1, oldestChart);
                    Statmt.executeUpdate();
                } catch (SQLException E) {
                    cfEngine.log("Error deleting data from BDCHARTDATA table: " + E);
                } finally {
                    if (Statmt != null)
                        try {
                            Statmt.close();
                        } catch (SQLException e) {
                        }
                    if (con != null)
                        try {
                            con.close();
                        } catch (SQLException ignore) {
                        }
                }
            }

            // Add the new chart to the end of the list of cached charts
            storageCache.add(name);
        }
    }

    return name;
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

@Override
public void insertMessageAttachment(String channelId, long messageId, Attachment attachment) {
    logger.debug(channelId + "/" + messageId + ": inserting message attachment");

    try {/*from  w w  w  .  j a  va2  s.  c  o  m*/
        PreparedStatement statement = prepareStatement("insertMessageAttachment", channelId);
        statement.setString(1, attachment.getId());
        statement.setLong(2, messageId);
        statement.setString(3, attachment.getType());

        // The size of each segment of the attachment.
        int chunkSize = 10000000;

        if (attachment.getContent().length <= chunkSize) {
            // If there is only one segment, just store it
            statement.setInt(4, 1);
            statement.setInt(5, attachment.getContent().length);
            statement.setBytes(6, attachment.getContent());
            statement.executeUpdate();
        } else {
            // Use an input stream on the attachment content to segment the data.
            ByteArrayInputStream inputStream = new ByteArrayInputStream(attachment.getContent());
            // The order of the segment
            int segmentIndex = 1;

            // As long as there are bytes left
            while (inputStream.available() > 0) {
                // Set the segment number
                statement.setInt(4, segmentIndex++);
                // Determine the segment size. If there are more bytes left than the chunk size, the size is the chunk size. Otherwise it is the number of remaining bytes
                int segmentSize = Math.min(chunkSize, inputStream.available());
                // Create a byte array to store the chunk
                byte[] segment = new byte[segmentSize];
                // Read the chunk from the input stream to the byte array
                inputStream.read(segment, 0, segmentSize);
                // Set the segment size
                statement.setInt(5, segmentSize);
                // Set the byte data
                statement.setBytes(6, segment);
                // Perform the insert
                statement.executeUpdate();
            }
        }

        // Clear the parameters because the data held in memory could be quite large.
        statement.clearParameters();
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}

From source file:org.openiot.gsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;
    String query = getStatementInsert(tableName, fields).toString();
    try {//w w  w .  j  a  v a 2s  .c o m
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                logger.error("The type conversion is not supported for : " + dataField.getName() + "("
                        + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        //if (e.getType() == GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        //    if (logger.isDebugEnabled())
        //        logger.debug("An stream element dropped due to unexpected virtual sensor removal. (Stream element: " + streamElement.toString() + ")+ Query: " + query, e);
        //} else
        logger.warn("Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            logger.info("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        else
            logger.warn("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        throw e;
    } finally {
        close(ps);
    }
}

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

private boolean insertTopData(Connection conn, List<TopNData> topNData, boolean continueOnSQLException)
        throws SQLException {
    if (log.isDebugEnabled()) {
        log.debug("Inserting Top Processes data - '" + topNData + "'");
    }/*www  .  j ava  2s  . c  o m*/
    PreparedStatement stmt = null;
    final StringBuilder buf = new StringBuilder();

    Map<Date, List<TopNData>> dayToDataMap = mapDayToData(topNData);

    for (Entry<Date, List<TopNData>> entry : dayToDataMap.entrySet()) {
        try {

            String partitionName = getAndCreatePartition(TopNData.class.getSimpleName(), entry.getKey(), conn);
            stmt = conn.prepareStatement(buf.append("INSERT INTO ").append(partitionName)
                    .append(" (resourceId, time, data) VALUES (?, ?, ?)").toString());

            for (TopNData data : entry.getValue()) {
                stmt.setInt(1, data.getResourceId());
                stmt.setTimestamp(2, new java.sql.Timestamp(data.getTime().getTime()));
                stmt.setBytes(3, data.getData());
                stmt.addBatch();
            }
            int[] execInfo = stmt.executeBatch();

        } catch (BatchUpdateException e) {
            if (!continueOnSQLException) {
                throw e;
            }
        } catch (SQLException e) {
            if (!continueOnSQLException) {
                throw e;
            }
            if (log.isDebugEnabled()) {
                log.debug("A general SQLException occurred during the insert of TopN. ", e);
            }

        } finally {
            DBUtil.closeStatement(LOG_CTX, stmt);
        }

    }
    return true;
}

From source file:tinygsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;
    String query = getStatementInsert(tableName, fields).toString();
    try {/*from www  .ja  va2  s .  co  m*/
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                // logger.error("The type conversion is not supported for : "
                // + dataField.getName() + "(" + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        // if (e.getType() ==
        // GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        // if (logger.isDebugEnabled())
        //
        // logger
        // .debug(
        // "An stream element dropped due to unexpected virtual sensor removal. (Stream element: "
        // + streamElement.toString() + ")+ Query: " + query, e);
        // } else
        // logger.warn(
        // "Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            // logger
            // .info("Error occurred on inserting data to the database, an stream element dropped due to: "
            // + e.getMessage()
            // + ". (Stream element: "
            // + streamElement.toString() + ")+ Query: " + query);
            // else
            // logger
            // .warn("Error occurred on inserting data to the database, an stream element dropped due to: "
            // + e.getMessage()
            // + ". (Stream element: "
            // + streamElement.toString() + ")+ Query: " + query);
            throw e;
    } finally {
        close(ps);
    }
}

From source file:org.quartz.impl.jdbcjobstore.StdJDBCDelegate.java

/**
 * Sets the designated parameter to the byte array of the given
 * <code>ByteArrayOutputStream</code>.  Will set parameter value to null if the 
 * <code>ByteArrayOutputStream</code> is null.
 * This just wraps <code>{@link PreparedStatement#setBytes(int, byte[])}</code>
 * by default, but it can be overloaded by subclass delegates for databases that
 * don't explicitly support storing bytes in this way.
 *///from  w w  w  . j  ava 2s . c  o  m
protected void setBytes(PreparedStatement ps, int index, ByteArrayOutputStream baos) throws SQLException {
    ps.setBytes(index, (baos == null) ? new byte[0] : baos.toByteArray());
}

From source file:com.alfaariss.oa.engine.tgt.jdbc.JDBCTGTFactory.java

/**
 * Uses a batch update to persist all supplied tgts.
 * @param tgts The TGTs to persist./* w  w w.j a  v  a2  s  .  co m*/
 * @throws PersistenceException If persistance fails.
 * 
 * @see IEntityManager#persist(IEntity[])
 * @see PreparedStatement#addBatch()
 */
public void persist(JDBCTGT[] tgts) throws PersistenceException {
    if (tgts == null)
        throw new IllegalArgumentException("Suplied tgt array is empty or invalid");

    List<TGTEventError> listTGTEventErrors = new Vector<TGTEventError>();

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

        if (_aliasStoreSP != null)
            psDeleteAliasR = connection.prepareStatement(_aliasStoreSP.getQueryAliasRemove());

        if (_aliasStoreIDP != null)
            psDeleteAliasF = connection.prepareStatement(_aliasStoreIDP.getQueryAliasRemove());

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

        Vector<ITGT> vCreate = new Vector<ITGT>();
        Vector<ITGT> vUpdate = new Vector<ITGT>();
        Vector<ITGT> vRemove = new Vector<ITGT>();

        for (JDBCTGT tgt : tgts) //For all tgts
        {
            String id = tgt.getId();
            if (id == null) //New TGT
            {
                byte[] baId = new byte[ITGT.TGT_LENGTH];
                do {
                    _random.nextBytes(baId);
                    try {
                        id = ModifiedBase64.encode(baId);
                    } catch (UnsupportedEncodingException e) {
                        _logger.error("Could not create tgt id for byte[]: " + baId, e);
                        throw new PersistenceException(SystemErrors.ERROR_INTERNAL);
                    }
                } while (exists(id)); //Key allready exists   

                tgt.setId(id);
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                tgt.setTgtExpTime(expiration);
                psInsert.setString(1, id);
                psInsert.setTimestamp(2, new Timestamp(expiration));
                psInsert.setBytes(3, Serialize.encode(tgt.getUser()));
                psInsert.setBytes(4, Serialize.encode(tgt.getAuthenticationProfile()));
                psInsert.setBytes(5, Serialize.encode(tgt.getModifiableAuthNProfileIDs()));
                psInsert.setBytes(6, Serialize.encode(tgt.getModifiableRequestorIDs()));
                psInsert.setBytes(7, Serialize.encode(tgt.getAttributes()));
                psInsert.addBatch();

                vCreate.add(tgt);
            } else if (tgt.isExpired()) //Expired
            {
                _logger.debug("TGT Expired: " + id);

                if (psDeleteAliasR != null) {
                    psDeleteAliasR.setString(1, id);
                    psDeleteAliasR.addBatch();
                }

                if (psDeleteAliasF != null) {
                    psDeleteAliasF.setString(1, id);
                    psDeleteAliasF.addBatch();
                }

                vRemove.add(tgt);
            } else //Update
            {
                //Update expiration time
                long expiration = System.currentTimeMillis() + _lExpiration;
                tgt.setTgtExpTime(expiration);
                //Update tgt
                psUpdate.setTimestamp(1, new Timestamp(expiration));
                psUpdate.setBytes(2, Serialize.encode(tgt.getUser()));
                psUpdate.setBytes(3, Serialize.encode(tgt.getAuthenticationProfile()));
                psUpdate.setBytes(4, Serialize.encode(tgt.getModifiableAuthNProfileIDs()));
                psUpdate.setBytes(5, Serialize.encode(tgt.getModifiableRequestorIDs()));
                psUpdate.setBytes(6, Serialize.encode(tgt.getAttributes()));
                psUpdate.setString(7, id);
                psUpdate.addBatch();

                vUpdate.add(tgt);
            }
        }

        try {
            int iTotalAdded = 0;
            for (int i : psInsert.executeBatch()) {
                iTotalAdded += i;
            }
            _logger.debug(iTotalAdded + " new TGT(s) added by batch");

            for (ITGT tgt : vCreate) {
                try {
                    processEvent(TGTListenerEvent.ON_CREATE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }
        } catch (SQLException e) {
            _logger.error("Could not execute insert batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_INSERT);
        }

        try {
            for (ITGT tgt : vRemove) {
                IUser tgtUser = tgt.getUser();
                _eventLogger.info(new UserEventLogItem(null, tgt.getId(), null, UserEvent.TGT_EXPIRED,
                        tgtUser.getID(), tgtUser.getOrganization(), null, null, this, null));

                try {
                    processEvent(TGTListenerEvent.ON_REMOVE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }

            int iTotalDeleted = 0;
            for (int i : psDelete.executeBatch()) {
                iTotalDeleted += i;
            }
            _logger.debug(iTotalDeleted + " TGT(s) deleted by batch");
        } catch (SQLException e) {
            _logger.error("Could not execute delete batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
        }

        if (psDeleteAliasR != null) {
            try {
                int iTotalAliasDeleted = 0;
                for (int i : psDeleteAliasR.executeBatch()) {
                    iTotalAliasDeleted += i;
                }
                _logger.debug(iTotalAliasDeleted + " (requestor based) alias(es) deleted by batch");
            } catch (SQLException e) {
                _logger.error("Could not execute delete (requestor based) alias batch", e);
                throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
            }
        }

        if (psDeleteAliasF != null) {
            try {
                int iTotalAliasDeleted = 0;
                for (int i : psDeleteAliasF.executeBatch()) {
                    iTotalAliasDeleted += i;
                }
                _logger.debug(iTotalAliasDeleted + " (remote enitity based) alias(es) deleted by batch");
            } catch (SQLException e) {
                _logger.error("Could not execute delete (remote enitity based) alias batch", e);
                throw new PersistenceException(SystemErrors.ERROR_RESOURCE_REMOVE);
            }
        }

        try {
            int iTotalUpdated = 0;
            for (int i : psUpdate.executeBatch()) {
                iTotalUpdated += i;
            }
            _logger.debug(iTotalUpdated + " TGT(s) updated by batch");

            for (ITGT tgt : vUpdate) {
                try {
                    processEvent(TGTListenerEvent.ON_UPDATE, tgt);
                } catch (TGTListenerException e) {
                    listTGTEventErrors.addAll(e.getErrors());
                }
            }
        } catch (SQLException e) {
            _logger.error("Could not execute update batch", e);
            throw new PersistenceException(SystemErrors.ERROR_RESOURCE_UPDATE);
        }

        connection.commit();

        if (listTGTEventErrors != null) {//TGT Event processing failed, error has been logged already
            throw new TGTListenerException(listTGTEventErrors);
        }
    } 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("Could not connect to JDBC resource", 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 (psDeleteAliasR != null)
                psDeleteAliasR.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete (requestor based) alias statement", e);
        }

        try {
            if (psDeleteAliasF != null)
                psDeleteAliasF.close();
        } catch (SQLException e) {
            _logger.debug("Could not close delete (remote entity based) alias 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:gsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;
    String query = getStatementInsert(tableName, fields).toString();
    try {/*  www.  j a  v  a  2 s  .  c o m*/
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.FLOAT:
                if (value == null)
                    ps.setNull(counter, Types.FLOAT);
                else
                    ps.setFloat(counter, ((Number) value).floatValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                logger.error("The type conversion is not supported for : " + dataField.getName() + "("
                        + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        //if (e.getType() == GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        //    if (logger.isDebugEnabled())
        //        logger.debug("An stream element dropped due to unexpected virtual sensor removal. (Stream element: " + streamElement.toString() + ")+ Query: " + query, e);
        //} else
        logger.warn("Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            logger.info("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        else
            logger.warn("Error occurred on inserting data to the database, an stream element dropped due to: "
                    + e.getMessage() + ". (Stream element: " + streamElement.toString() + ")+ Query: " + query);
        throw e;
    } finally {
        close(ps);
    }
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "INSERT" on the given table and and table prefix for
 * the supplied attributeValues/*from   ww  w.  java  2  s  .co m*/
 * 
 * @param table
 * @param attributeValues
 * @return
 * @throws SQLException
 */
public boolean insertRow(String table, Map attributeValues) throws SQLException {

    PreparedStatement prepStmt = null;
    Object attribute = null;
    boolean success = false;

    try {
        prepStmt = sqlConnection_.prepareStatement(getSQLTableConstants().getInsertStatementSQL(table));

        for (int i = 0; i < attributeValues.size(); i++) {

            attribute = attributeValues.get("" + (i + 1));

            // If null, we are unable to determine the SQL param type,
            // so String is assumed by default.
            if (attribute == null) {
                prepStmt.setString(i + 1, null);
            } else if (attribute instanceof String) {
                prepStmt.setString(i + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(i + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(i + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(i + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(i + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(i + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(i + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(i + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(i + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(i + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(i + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(i + 1, (Timestamp) attribute);
            }
        }

        success = prepStmt.execute();
    } finally {
        prepStmt.close();
    }

    return success;
}

From source file:org.getobjects.eoaccess.EOAdaptorChannel.java

protected void _setStatementParameter(final PreparedStatement _stmt, final int _idx, final int _type,
        final Object _value) throws SQLException {
    if (_stmt == null)
        return;//from  w  w  w  . ja va  2s  .c o m

    /* NULL */

    if (_value == null) {
        _stmt.setNull(_idx, _type);
        return;
    }

    /* values */

    switch (_type) {
    case java.sql.Types.NULL:
        _stmt.setNull(_idx, java.sql.Types.VARCHAR); // CRAP
        break;

    // TODO: customize value processing for types
    case java.sql.Types.VARCHAR:
    case java.sql.Types.TIMESTAMP:
    case java.sql.Types.DATE:
    case java.sql.Types.INTEGER:
    case java.sql.Types.BOOLEAN:
    default:
        if (_value instanceof String)
            _stmt.setString(_idx, (String) _value);
        else if (_value instanceof Boolean)
            _stmt.setBoolean(_idx, (Boolean) _value);
        else if (_value instanceof Integer)
            _stmt.setInt(_idx, (Integer) _value);
        else if (_value instanceof Long)
            _stmt.setLong(_idx, (Long) _value);
        else if (_value instanceof Double)
            _stmt.setDouble(_idx, (Double) _value);
        else if (_value instanceof BigDecimal)
            _stmt.setBigDecimal(_idx, (BigDecimal) _value);
        else if (_value instanceof java.util.Date) {
            _stmt.setTimestamp(_idx, new java.sql.Timestamp(((Date) _value).getTime()));
        } else if (_value instanceof java.sql.Date) {
            /* Note: this is just the DATE component, no TIME */
            _stmt.setDate(_idx, (java.sql.Date) _value);
        } else if (_value instanceof java.util.Calendar) {
            // TBD: shouldn't we use setDate with a proper Calendar?
            final Date vd = ((Calendar) _value).getTime();
            _stmt.setTimestamp(_idx, new java.sql.Timestamp(vd.getTime()));
        } else if (_value instanceof byte[])
            _stmt.setBytes(_idx, (byte[]) _value);
        else {
            log.warn("using String column for value: " + _value + " (" + _value.getClass() + ")");
        }
    }
}