Example usage for java.sql PreparedStatement setDouble

List of usage examples for java.sql PreparedStatement setDouble

Introduction

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

Prototype

void setDouble(int parameterIndex, double x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java double value.

Usage

From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java

/**
 * This method bind values to prepared statement.
 *
 * @param type            data Type//from   w  w w.  ja v  a2  s . c o m
 * @param value           String value
 * @param ordinalPosition Ordinal Position
 * @param sqlStatement    Statement
 * @throws SQLException
 * @throws ParseException
 * @throws ODataServiceFault
 */
private void bindValuesToPreparedStatement(int type, String value, int ordinalPosition,
        PreparedStatement sqlStatement) throws SQLException, ParseException, ODataServiceFault {
    byte[] data;
    try {
        switch (type) {
        case Types.INTEGER:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setInt(ordinalPosition, ConverterUtil.convertToInt(value));
            }
            break;
        case Types.TINYINT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setByte(ordinalPosition, ConverterUtil.convertToByte(value));
            }
            break;
        case Types.SMALLINT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setShort(ordinalPosition, ConverterUtil.convertToShort(value));
            }
            break;
        case Types.DOUBLE:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setDouble(ordinalPosition, ConverterUtil.convertToDouble(value));
            }
            break;
        case Types.VARCHAR:
            /* fall through */
        case Types.CHAR:
            /* fall through */
        case Types.LONGVARCHAR:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setString(ordinalPosition, value);
            }
            break;
        case Types.CLOB:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setClob(ordinalPosition, new BufferedReader(new StringReader(value)),
                        value.length());
            }
            break;
        case Types.BOOLEAN:
            /* fall through */
        case Types.BIT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setBoolean(ordinalPosition, ConverterUtil.convertToBoolean(value));
            }
            break;
        case Types.BLOB:
            /* fall through */
        case Types.LONGVARBINARY:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                data = this.getBytesFromBase64String(value);
                sqlStatement.setBlob(ordinalPosition, new ByteArrayInputStream(data), data.length);
            }
            break;
        case Types.BINARY:
            /* fall through */
        case Types.VARBINARY:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                data = this.getBytesFromBase64String(value);
                sqlStatement.setBinaryStream(ordinalPosition, new ByteArrayInputStream(data), data.length);
            }
            break;
        case Types.DATE:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setDate(ordinalPosition, DBUtils.getDate(value));
            }
            break;
        case Types.DECIMAL:
            /* fall through */
        case Types.NUMERIC:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setBigDecimal(ordinalPosition, ConverterUtil.convertToBigDecimal(value));
            }
            break;
        case Types.FLOAT:
            /* fall through */
        case Types.REAL:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setFloat(ordinalPosition, ConverterUtil.convertToFloat(value));
            }
            break;
        case Types.TIME:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setTime(ordinalPosition, DBUtils.getTime(value));
            }
            break;
        case Types.LONGNVARCHAR:
            /* fall through */
        case Types.NCHAR:
            /* fall through */
        case Types.NVARCHAR:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setNString(ordinalPosition, value);
            }
            break;
        case Types.NCLOB:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setNClob(ordinalPosition, new BufferedReader(new StringReader(value)),
                        value.length());
            }
            break;
        case Types.BIGINT:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setLong(ordinalPosition, ConverterUtil.convertToLong(value));
            }
            break;
        case Types.TIMESTAMP:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setTimestamp(ordinalPosition, DBUtils.getTimestamp(value));
            }
            break;
        default:
            if (value == null) {
                sqlStatement.setNull(ordinalPosition, type);
            } else {
                sqlStatement.setString(ordinalPosition, value);
            }
            break;
        }
    } catch (DataServiceFault e) {
        throw new ODataServiceFault(e, "Error occurred while binding values. :" + e.getMessage());
    }
}

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 {//from  w w  w  .  j a  va  2s.  co  m
        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:org.wso2.carbon.dataservices.core.description.query.SQLQuery.java

private void setDoubleValue(int queryType, String value, String paramType, PreparedStatement sqlQuery, int i)
        throws SQLException {
    Double val = null;
    if (value != null) {
        val = Double.parseDouble(value);
    }//ww  w .j  av a  2s.  c o  m
    if (QueryTypes.IN.equals(paramType)) {
        if (queryType == SQLQuery.DS_QUERY_TYPE_NORMAL) {
            if (value == null) {
                sqlQuery.setNull(i + 1, java.sql.Types.DOUBLE);
            } else {
                sqlQuery.setDouble(i + 1, val);
            }
        } else {
            if (value == null) {
                ((CallableStatement) sqlQuery).setNull(i + 1, java.sql.Types.DOUBLE);
            } else {
                ((CallableStatement) sqlQuery).setDouble(i + 1, val);
            }
        }
    } else if (QueryTypes.INOUT.equals(paramType)) {
        if (value == null) {
            ((CallableStatement) sqlQuery).setNull(i + 1, java.sql.Types.DOUBLE);
        } else {
            ((CallableStatement) sqlQuery).setDouble(i + 1, val);
        }
        ((CallableStatement) sqlQuery).registerOutParameter(i + 1, java.sql.Types.DOUBLE);
    } else {
        ((CallableStatement) sqlQuery).registerOutParameter(i + 1, java.sql.Types.DOUBLE);
    }
}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

/**
 * Load a double literal with the double value given as argument if it exists. The method will first look in
 * the node cache for cached nodes. If no cache entry is found, it will run a database query ("load.literal_by_dv")
 * on the NODES table and construct a new KiWiLiteral using the values of the literal columns
 * (svalue, ivalue, ...). The type of literal returned depends on the value of the ntype column.
 * <p/>/*w ww  .j  a v a  2  s  .c o m*/
 * When a node is loaded from the database, it will be added to the different caches to speed up
 * subsequent requests.
 *
 * @param value the value of the integer literal to load
 * @return a KiWiDoubleLiteral with the correct value, or null if it does not exist
 * @throws SQLException
 */
public KiWiDoubleLiteral loadLiteral(double value) throws SQLException {
    // look in cache
    KiWiLiteral element = literalCache.get(
            LiteralCommons.createCacheKey(Double.toString(value), (String) null, Namespaces.NS_XSD + "double"));
    if (element != null && element instanceof KiWiDoubleLiteral) {
        return (KiWiDoubleLiteral) element;
    }

    requireJDBCConnection();

    KiWiUriResource ltype = loadUriResource(Namespaces.NS_XSD + "double");

    // ltype not persisted
    if (ltype == null || ltype.getId() < 0) {
        return null;
    }

    literalLock.lock();

    try {
        // otherwise prepare a query, depending on the parameters given
        PreparedStatement query = getPreparedStatement("load.literal_by_dv");
        query.setDouble(1, value);
        query.setLong(2, ltype.getId());

        // run the database query and if it yields a result, construct a new node; the method call will take care of
        // caching the constructed node for future calls
        ResultSet result = query.executeQuery();
        KiWiNode kiWiNode = null;
        try {
            if (result.next()) {
                return (KiWiDoubleLiteral) constructNodeFromDatabase(result);
            } else {
                return null;
            }
        } catch (RuntimeException e) {
            log.error("Unable to create KiWiDoubleLiteral for node value '{}' (id={}): {}", value,
                    kiWiNode.getId(), e.getMessage(), e);
            throw e;
        } finally {
            result.close();
        }
    } finally {
        literalLock.unlock();
    }
}

From source file:dk.netarkivet.harvester.datamodel.RunningJobsInfoDBDAO.java

/**
 * Store frontier report data to the persistent storage.
 * @param report the report to store/*w  w  w  .ja v a 2  s  . co m*/
 * @param filterId the id of the filter that produced the report
 * @param jobId The ID of the job responsible for this report
 * @return the update count
 */
public int storeFrontierReport(String filterId, InMemoryFrontierReport report, Long jobId) {
    ArgumentNotValid.checkNotNull(report, "report");
    ArgumentNotValid.checkNotNull(jobId, "jobId");

    Connection c = HarvestDBConnection.get();
    PreparedStatement stm = null;
    try {

        // First drop existing rows
        try {
            c.setAutoCommit(false);

            stm = c.prepareStatement("DELETE FROM frontierReportMonitor" + " WHERE jobId=? AND filterId=?");
            stm.setLong(1, jobId);
            stm.setString(2, filterId);

            stm.executeUpdate();

            c.commit();
        } catch (SQLException e) {
            String message = "SQL error dropping records for job ID " + jobId + " and filterId " + filterId
                    + "\n" + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            return 0;
        } finally {
            DBUtils.closeStatementIfOpen(stm);
            DBUtils.rollbackIfNeeded(c, "storeFrontierReport delete", jobId);
        }

        // Now batch insert report lines
        try {
            c.setAutoCommit(false);

            stm = c.prepareStatement("INSERT INTO frontierReportMonitor(" + FR_COLUMN.getColumnsInOrder()
                    + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

            for (FrontierReportLine frl : report.getLines()) {
                stm.setLong(FR_COLUMN.jobId.rank(), jobId);
                stm.setString(FR_COLUMN.filterId.rank(), filterId);
                stm.setTimestamp(FR_COLUMN.tstamp.rank(), new Timestamp(report.getTimestamp()));
                stm.setString(FR_COLUMN.domainName.rank(), frl.getDomainName());
                stm.setLong(FR_COLUMN.currentSize.rank(), frl.getCurrentSize());
                stm.setLong(FR_COLUMN.totalEnqueues.rank(), frl.getTotalEnqueues());
                stm.setLong(FR_COLUMN.sessionBalance.rank(), frl.getSessionBalance());
                stm.setDouble(FR_COLUMN.lastCost.rank(), frl.getLastCost());
                stm.setDouble(FR_COLUMN.averageCost.rank(),
                        correctNumericIfIllegalAverageCost(frl.getAverageCost()));
                stm.setString(FR_COLUMN.lastDequeueTime.rank(), frl.getLastDequeueTime());
                stm.setString(FR_COLUMN.wakeTime.rank(), frl.getWakeTime());
                stm.setLong(FR_COLUMN.totalSpend.rank(), frl.getTotalSpend());
                stm.setLong(FR_COLUMN.totalBudget.rank(), frl.getTotalBudget());
                stm.setLong(FR_COLUMN.errorCount.rank(), frl.getErrorCount());

                // URIs are to be truncated to 1000 characters
                // (see SQL scripts)
                DBUtils.setStringMaxLength(stm, FR_COLUMN.lastPeekUri.rank(), frl.getLastPeekUri(),
                        MAX_URL_LENGTH, frl, "lastPeekUri");
                DBUtils.setStringMaxLength(stm, FR_COLUMN.lastQueuedUri.rank(), frl.getLastQueuedUri(),
                        MAX_URL_LENGTH, frl, "lastQueuedUri");

                stm.addBatch();
            }

            int[] updCounts = stm.executeBatch();
            int updCountTotal = 0;
            for (int count : updCounts) {
                updCountTotal += count;
            }

            c.commit();

            return updCountTotal;
        } catch (SQLException e) {
            String message = "SQL error writing records for job ID " + jobId + " and filterId " + filterId
                    + "\n" + ExceptionUtils.getSQLExceptionCause(e);
            log.warn(message, e);
            return 0;
        } finally {
            DBUtils.closeStatementIfOpen(stm);
            DBUtils.rollbackIfNeeded(c, "storeFrontierReport insert", jobId);
        }

    } finally {
        HarvestDBConnection.release(c);
    }
}

From source file:com.oltpbenchmark.benchmarks.tpcc.TPCCLoader.java

protected int loadDist(int whseKount, int distWhseKount) {

    int k = 0;/* ww w  .ja  v  a  2 s  .  com*/
    int t = 0;

    try {

        String sql = SQLUtil.getInsertSQL(this.getTableCatalog(TPCCConstants.TABLENAME_DISTRICT));
        PreparedStatement distPrepStmt = this.conn.prepareStatement(sql);

        now = new java.util.Date();

        if (outputFiles == true) {
            out = new PrintWriter(new FileOutputStream(fileLocation + "district.csv"));
            LOG.debug("\nWriting District file to: " + fileLocation + "district.csv");
        }

        District district = new District();

        t = (whseKount * distWhseKount);
        LOG.debug("\nStart District Data for " + t + " Dists @ " + now + " ...");

        for (int w = 1; w <= whseKount; w++) {

            for (int d = 1; d <= distWhseKount; d++) {

                district.d_id = d;
                district.d_w_id = w;
                district.d_ytd = 30000;

                // random within [0.0000 .. 0.2000]
                district.d_tax = (float) ((TPCCUtil.randomNumber(0, 2000, gen)) / 10000.0);

                district.d_next_o_id = 3001;
                district.d_name = TPCCUtil.randomStr(TPCCUtil.randomNumber(6, 10, gen));
                district.d_street_1 = TPCCUtil.randomStr(TPCCUtil.randomNumber(10, 20, gen));
                district.d_street_2 = TPCCUtil.randomStr(TPCCUtil.randomNumber(10, 20, gen));
                district.d_city = TPCCUtil.randomStr(TPCCUtil.randomNumber(10, 20, gen));
                district.d_state = TPCCUtil.randomStr(3).toUpperCase();
                district.d_zip = "123456789";

                k++;
                if (outputFiles == false) {
                    distPrepStmt.setLong(1, district.d_w_id);
                    distPrepStmt.setLong(2, district.d_id);
                    distPrepStmt.setDouble(3, district.d_ytd);
                    distPrepStmt.setDouble(4, district.d_tax);
                    distPrepStmt.setLong(5, district.d_next_o_id);
                    distPrepStmt.setString(6, district.d_name);
                    distPrepStmt.setString(7, district.d_street_1);
                    distPrepStmt.setString(8, district.d_street_2);
                    distPrepStmt.setString(9, district.d_city);
                    distPrepStmt.setString(10, district.d_state);
                    distPrepStmt.setString(11, district.d_zip);
                    distPrepStmt.executeUpdate();
                } else {
                    String str = "";
                    str = str + district.d_id + ",";
                    str = str + district.d_w_id + ",";
                    str = str + district.d_ytd + ",";
                    str = str + district.d_tax + ",";
                    str = str + district.d_next_o_id + ",";
                    str = str + district.d_name + ",";
                    str = str + district.d_street_1 + ",";
                    str = str + district.d_street_2 + ",";
                    str = str + district.d_city + ",";
                    str = str + district.d_state + ",";
                    str = str + district.d_zip;
                    out.println(str);
                }

            } // end for [d]

        } // end for [w]

        long tmpTime = new java.util.Date().getTime();
        String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + "                    ";
        LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
        lastTimeMS = tmpTime;
        transCommit();
        now = new java.util.Date();
        LOG.debug("End District Load @  " + now);

    } catch (SQLException se) {
        LOG.debug(se.getMessage());
        transRollback();
    } catch (Exception e) {
        e.printStackTrace();
        transRollback();
    }

    return (k);

}

From source file:com.oltpbenchmark.benchmarks.tpcc.TPCCLoader.java

protected int loadItem(int itemKount) {

    int k = 0;/*from   w  w w. j av  a2s. co m*/
    int t = 0;
    int randPct = 0;
    int len = 0;
    int startORIGINAL = 0;

    try {
        PreparedStatement itemPrepStmt = getInsertStatement(TPCCConstants.TABLENAME_ITEM);

        now = new java.util.Date();
        t = itemKount;
        LOG.debug("\nStart Item Load for " + t + " Items @ " + now + " ...");

        if (outputFiles == true) {
            out = new PrintWriter(new FileOutputStream(fileLocation + "item.csv"));
            LOG.debug("\nWriting Item file to: " + fileLocation + "item.csv");
        }

        Item item = new Item();

        for (int i = 1; i <= itemKount; i++) {

            item.i_id = i;
            item.i_name = TPCCUtil.randomStr(TPCCUtil.randomNumber(14, 24, gen));
            item.i_price = (float) (TPCCUtil.randomNumber(100, 10000, gen) / 100.0);

            // i_data
            randPct = TPCCUtil.randomNumber(1, 100, gen);
            len = TPCCUtil.randomNumber(26, 50, gen);
            if (randPct > 10) {
                // 90% of time i_data isa random string of length [26 .. 50]
                item.i_data = TPCCUtil.randomStr(len);
            } else {
                // 10% of time i_data has "ORIGINAL" crammed somewhere in
                // middle
                startORIGINAL = TPCCUtil.randomNumber(2, (len - 8), gen);
                item.i_data = TPCCUtil.randomStr(startORIGINAL - 1) + "ORIGINAL"
                        + TPCCUtil.randomStr(len - startORIGINAL - 9);
            }

            item.i_im_id = TPCCUtil.randomNumber(1, 10000, gen);

            k++;

            if (outputFiles == false) {
                itemPrepStmt.setLong(1, item.i_id);
                itemPrepStmt.setString(2, item.i_name);
                itemPrepStmt.setDouble(3, item.i_price);
                itemPrepStmt.setString(4, item.i_data);
                itemPrepStmt.setLong(5, item.i_im_id);
                itemPrepStmt.addBatch();

                if ((k % configCommitCount) == 0) {
                    long tmpTime = new java.util.Date().getTime();
                    String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000)
                            + "                    ";
                    LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                    lastTimeMS = tmpTime;
                    itemPrepStmt.executeBatch();
                    itemPrepStmt.clearBatch();
                    transCommit();
                }
            } else {
                String str = "";
                str = str + item.i_id + ",";
                str = str + item.i_name + ",";
                str = str + item.i_price + ",";
                str = str + item.i_data + ",";
                str = str + item.i_im_id;
                out.println(str);

                if ((k % configCommitCount) == 0) {
                    long tmpTime = new java.util.Date().getTime();
                    String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000)
                            + "                    ";
                    LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
                    lastTimeMS = tmpTime;
                }
            }

        } // end for

        long tmpTime = new java.util.Date().getTime();
        String etStr = "  Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + "                    ";
        LOG.debug(etStr.substring(0, 30) + "  Writing record " + k + " of " + t);
        lastTimeMS = tmpTime;

        if (outputFiles == false) {
            itemPrepStmt.executeBatch();
        }

        transCommit();
        now = new java.util.Date();
        LOG.debug("End Item Load @  " + now);

    } catch (SQLException se) {
        LOG.debug(se.getMessage());
        transRollback();
    } catch (Exception e) {
        e.printStackTrace();
        transRollback();
    }

    return (k);

}

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 {/*from w w w  . j  av 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.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: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  ava  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.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  ww w.  ja  v a2  s .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() + ")");
        }
    }
}