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.eclipse.ecr.core.storage.sql.jdbc.dialect.DialectPostgreSQL.java

@Override
public void setToPreparedStatement(PreparedStatement ps, int index, Serializable value, Column column)
        throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
    case Types.CLOB:
        setToPreparedStatementString(ps, index, value, column);
        return;/* ww w  .ja v a2 s .  co m*/
    case Types.BIT:
        ps.setBoolean(index, ((Boolean) value).booleanValue());
        return;
    case Types.SMALLINT:
        ps.setInt(index, ((Long) value).intValue());
        return;
    case Types.INTEGER:
    case Types.BIGINT:
        ps.setLong(index, ((Long) value).longValue());
        return;
    case Types.DOUBLE:
        ps.setDouble(index, ((Double) value).doubleValue());
        return;
    case Types.TIMESTAMP:
        setToPreparedStatementTimestamp(ps, index, value, column);
        return;
    case Types.ARRAY:
        Array array = createArrayOf(Types.VARCHAR, (Object[]) value, ps.getConnection());
        ps.setArray(index, array);
        return;
    case Types.OTHER:
        if (column.getType() == ColumnType.FTSTORED) {
            ps.setString(index, (String) value);
            return;
        }
        throw new SQLException("Unhandled type: " + column.getType());
    default:
        throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
    }
}

From source file:com.akman.excel.controller.CURDInvoice.java

public static void Save(Invoice inv) {

    Connection conn = Javaconnect.ConnecrDb();
    PreparedStatement pst = null;
    ResultSet rs = null;//from www .java2 s  . c om
    try {

        String sql = "INSERT INTO Invoice "
                + "(InvoiceNo,OrderNo, Date,TinNo,ReferenceNo,CountryOfOrigin,MOP,PaymentTerms,TrackingNo,S_Name,"
                + "   S_Address1, S_Address2, S_Address3, S_City, S_State, S_PinCode, S_PhoneNo, S_Country, B_Name, B_Address1, B_Address2, B_Address3, B_City,"
                + "   B_State, B_PinCode,   B_PhoneNo, B_Country, PakegeType, Quantity, Rate, Description, CatagoryItem, Category)"
                + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

        pst = conn.prepareStatement(sql);

        pst.setString(1, inv.getInvoiceNo());
        pst.setString(2, inv.getOrderNo());
        pst.setString(3, inv.getDate());
        pst.setString(4, inv.getTinNo());
        pst.setString(5, inv.getReferenceNo());
        pst.setString(6, inv.getCountryOfOrigin());
        pst.setString(7, inv.getMOP());
        pst.setString(8, inv.getPaymentTerms());
        pst.setString(9, inv.getTrackingNo());
        pst.setString(10, inv.getSender().getName());
        pst.setString(11, inv.getSender().getAddress1());
        pst.setString(12, inv.getSender().getAddress2());
        pst.setString(13, inv.getSender().getAddress3());
        pst.setString(14, inv.getSender().getCity());
        pst.setString(15, inv.getSender().getState());
        pst.setString(16, inv.getSender().getPinCode());
        pst.setString(17, inv.getSender().getPhoneNo());
        pst.setString(18, inv.getSender().getCountry());
        pst.setString(19, inv.getBuyer().getName());
        pst.setString(20, inv.getBuyer().getAddress1());
        pst.setString(21, inv.getBuyer().getAddress2());
        pst.setString(22, inv.getBuyer().getAddress3());
        pst.setString(23, inv.getBuyer().getCity());
        pst.setString(24, inv.getBuyer().getState());
        pst.setString(25, inv.getBuyer().getPinCode());
        pst.setString(26, inv.getBuyer().getPhoneNo());
        pst.setString(27, inv.getBuyer().getCountry());
        pst.setString(28, inv.getOrder().getPakegeType());
        pst.setDouble(29, inv.getOrder().getQuantity());
        pst.setDouble(30, inv.getOrder().getRate());
        pst.setString(31, inv.getOrder().getDescription());
        pst.setString(32, inv.getCatagoryItem());
        pst.setString(33, inv.getCategory());

        pst.execute();

    } catch (SQLException ex) {
        Logger.getLogger(CURDInvoice.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(pst);
        DbUtils.closeQuietly(conn);
    }
}

From source file:datawarehouse.CSVLoader.java

/**
 * Parse CSV file using OpenCSV library and load in given database table.
 *
 * @param csvFile Input CSV file// ww  w .  jav a2s .  co m
 * @param tableName Database table name to import data
 * @param truncateBeforeLoad Truncate the table before inserting new
 * records.
 * @throws Exception
 */
public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad) throws Exception {

    CSVReader csvReader = null;
    if (null == this.connection) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = new CSVReader(new FileReader(csvFile), this.seprator);

    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    System.out.println("Query: " + query);

    String[] nextLine;
    Connection con = null;
    PreparedStatement ps = null;
    try {
        con = this.connection;
        con.setAutoCommit(false);
        ps = con.prepareStatement(query);

        if (truncateBeforeLoad) {
            //delete data from table before loading csv
            con.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        while ((nextLine = csvReader.readNext()) != null) {
            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    //System.out.print(string + ": ");
                    try {
                        DateFormat format = new SimpleDateFormat("dd.mm.yyyy");
                        Date date = format.parse(string);
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                        //System.out.println("date");
                    } catch (ParseException | SQLException e) {
                        try {
                            Double income = parseDouble(string.replace(",", "."));
                            ps.setDouble(index++, income);
                            //System.out.println("double");
                        } catch (NumberFormatException | SQLException err) {
                            ps.setString(index++, string);
                            //System.out.println("string");
                        }
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        con.commit();
    } catch (Exception e) {
        con.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps) {
            ps.close();
        }
        if (null != con) {
            con.close();
        }

        csvReader.close();
    }
}

From source file:org.wso2.carbon.event.output.adapter.rdbms.RDBMSEventAdapter.java

/**
 * Populating column values to table Insert query
 *///from  www.j av a  2  s. c  o  m
private void populateStatement(Map<String, Object> map, PreparedStatement stmt, List<Attribute> colOrder)
        throws OutputEventAdapterException {
    Attribute attribute = null;

    try {
        for (int i = 0; i < colOrder.size(); i++) {
            attribute = colOrder.get(i);
            Object value = map.get(attribute.getName());
            if (value != null) {
                switch (attribute.getType()) {
                case INT:
                    stmt.setInt(i + 1, (Integer) value);
                    break;
                case LONG:
                    stmt.setLong(i + 1, (Long) value);
                    break;
                case FLOAT:
                    stmt.setFloat(i + 1, (Float) value);
                    break;
                case DOUBLE:
                    stmt.setDouble(i + 1, (Double) value);
                    break;
                case STRING:
                    stmt.setString(i + 1, (String) value);
                    break;
                case BOOL:
                    stmt.setBoolean(i + 1, (Boolean) value);
                    break;
                }
            } else {
                throw new OutputEventAdapterException("Cannot Execute Insert/Update. Null value detected for "
                        + "attribute" + attribute.getName());
            }
        }
    } catch (SQLException e) {
        cleanupConnections(stmt, null);
        throw new OutputEventAdapterException("Cannot set value to attribute name " + attribute.getName() + ". "
                + "Hence dropping the event." + e.getMessage(), e);
    }
}

From source file:org.ensembl.healthcheck.util.ConnectionBasedSqlTemplateImpl.java

private void bindParamsToPreparedStatement(PreparedStatement st, Object[] arguments) throws SQLException {
    int i = 0;/*  w  w w .j  a  va  2s  .c om*/
    if (arguments != null) {

        for (Object arg : arguments) {
            i++;
            if (arg == null) {
                st.setNull(i, Types.NULL);
            } else if (arg instanceof String) {
                st.setString(i, (String) arg);
            } else if (arg instanceof Integer) {
                st.setInt(i, (Integer) arg);
            } else if (arg instanceof Boolean) {
                st.setBoolean(i, (Boolean) arg);
            } else if (arg instanceof Short) {
                st.setShort(i, (Short) arg);
            } else if (arg instanceof Date) {
                st.setTimestamp(i, new java.sql.Timestamp(((Date) arg).getTime()));
            } else if (arg instanceof java.sql.Date) {
                st.setDate(i, new java.sql.Date(((Date) arg).getTime()));
            } else if (arg instanceof Double) {
                st.setDouble(i, (Double) arg);
            } else if (arg instanceof Long) {
                st.setLong(i, (Long) arg);
            } else if (arg instanceof BigDecimal) {
                st.setObject(i, arg);
            } else if (arg instanceof BigInteger) {
                st.setObject(i, arg);
            } else { // Object
                try {
                    ByteArrayOutputStream bytesS = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(bytesS);
                    out.writeObject(arg);
                    out.close();
                    byte[] bytes = bytesS.toByteArray();
                    bytesS.close();
                    st.setBytes(i, bytes);
                } catch (IOException e) {
                    throw new SQLException(
                            "Could not serialize object " + arg + " for use in a PreparedStatement ");
                }
            }
        }
    }
}

From source file:org.rhq.enterprise.server.measurement.MeasurementDataManagerBean.java

/**
 * Add metrics data to the database. Data that is passed can come from several Schedules, but needs to be of only
 * one type of MeasurementGathering. For good performance it is important that the agent sends batches as big as
 * possible (ok, perhaps not more than 100 items at a time).
 *
 * @param data the actual data points//from w  w w .  j a v  a 2 s  . c om
 */
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addNumericData(Set<MeasurementDataNumeric> data) {
    if ((data == null) || (data.isEmpty())) {
        return;
    }

    int expectedCount = data.size();

    Connection conn = null;
    DatabaseType dbType = null;

    Map<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();

    try {
        conn = rhqDs.getConnection();
        dbType = DatabaseTypeFactory.getDatabaseType(conn);

        if (dbType instanceof Postgresql83DatabaseType) {
            Statement st = null;
            try {
                // Take advantage of async commit here
                st = conn.createStatement();
                st.execute("SET synchronous_commit = off");
            } finally {
                JDBCUtil.safeClose(st);
            }
        }

        for (MeasurementDataNumeric aData : data) {
            Double value = aData.getValue();
            if ((value == null) || Double.isNaN(value) || Double.isInfinite(value)) {
                expectedCount--;
                continue;
            }

            String table = MeasurementDataManagerUtility.getTable(aData.getTimestamp());

            PreparedStatement ps = statements.get(table);

            if (ps == null) {
                String insertSql = "INSERT  /*+ APPEND */ INTO " + table
                        + "(schedule_id,time_stamp,value) VALUES(?,?,?)";
                ps = conn.prepareStatement(insertSql);
                statements.put(table, ps);
            }

            ps.setInt(1, aData.getScheduleId());
            ps.setLong(2, aData.getTimestamp());
            ps.setDouble(3, value);
            ps.addBatch();
        }

        int count = 0;
        for (PreparedStatement ps : statements.values()) {
            int[] res = ps.executeBatch();
            for (int updates : res) {
                if ((updates != 1) && (updates != -2)) // oracle returns -2 on success
                {
                    throw new MeasurementStorageException("Unexpected batch update size [" + updates + "]");
                }

                count++;
            }
        }

        if (count != expectedCount) {
            throw new MeasurementStorageException("Failure to store measurement data.");
        }

        notifyAlertConditionCacheManager("mergeMeasurementReport",
                data.toArray(new MeasurementData[data.size()]));
    } catch (SQLException e) {
        log.warn("Failure saving measurement numeric data:\n" + ThrowableUtil.getAllMessages(e));
    } catch (Exception e) {
        log.error("Error persisting numeric data", e);
    } finally {
        for (PreparedStatement ps : statements.values()) {
            JDBCUtil.safeClose(ps);
        }

        JDBCUtil.safeClose(conn);
    }
}

From source file:org.apache.hadoop.yarn.server.applicationhistoryservice.metrics.timeline.AbstractMiniHBaseClusterTest.java

protected void insertMetricRecords(Connection conn, TimelineMetrics metrics, long currentTime)
        throws SQLException, IOException {

    List<TimelineMetric> timelineMetrics = metrics.getMetrics();
    if (timelineMetrics == null || timelineMetrics.isEmpty()) {
        LOG.debug("Empty metrics insert request.");
        return;/*from   www  . j  av a  2s . com*/
    }

    PreparedStatement metricRecordStmt = null;

    try {
        metricRecordStmt = conn.prepareStatement(String.format(UPSERT_METRICS_SQL, METRICS_RECORD_TABLE_NAME));

        for (TimelineMetric metric : timelineMetrics) {
            metricRecordStmt.clearParameters();

            if (LOG.isTraceEnabled()) {
                LOG.trace("host: " + metric.getHostName() + ", " + "metricName = " + metric.getMetricName()
                        + ", " + "values: " + metric.getMetricValues());
            }
            double[] aggregates = AggregatorUtils.calculateAggregates(metric.getMetricValues());

            metricRecordStmt.setString(1, metric.getMetricName());
            metricRecordStmt.setString(2, metric.getHostName());
            metricRecordStmt.setString(3, metric.getAppId());
            metricRecordStmt.setString(4, metric.getInstanceId());
            metricRecordStmt.setLong(5, currentTime);
            metricRecordStmt.setLong(6, metric.getStartTime());
            metricRecordStmt.setString(7, metric.getType());
            metricRecordStmt.setDouble(8, aggregates[0]);
            metricRecordStmt.setDouble(9, aggregates[1]);
            metricRecordStmt.setDouble(10, aggregates[2]);
            metricRecordStmt.setLong(11, (long) aggregates[3]);
            String json = TimelineUtils.dumpTimelineRecordtoJSON(metric.getMetricValues());
            metricRecordStmt.setString(12, json);

            try {
                metricRecordStmt.executeUpdate();
            } catch (SQLException sql) {
                LOG.error(sql);
            }
        }

        conn.commit();

    } finally {
        if (metricRecordStmt != null) {
            try {
                metricRecordStmt.close();
            } catch (SQLException e) {
                // Ignore
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sql) {
                // Ignore
            }
        }
    }
}

From source file:org.athenasource.framework.unidbi.Datatypes.java

/**
 * Setting the parameter for the given prepared statement. This method will
 * cast the value to the object expected type (execept BOOLEAN) as
 * {@linkplain #getClass(int)}.//w  w w .  j  a  v  a 2  s. c  o  m
 * <p>INSERT, UPDATE should always call this method to set parameters before 'WHERE' keyword.</p>
 * <p><b>Warining</b>: For parameters after 'WHERE' keyword, always remember 'IS NULL' is not equal to '= NULL'.</p>
 *
 * @param index
 *            the parameter index
 * @param value
 *            the value for the parameter, can be <code>null</code>.
 * @param unidbType
 *            the datatype of the parameter
 * @throws SQLException
 *             in case of SQL problems or type conversion fails.
 */
public static void setParameter(PreparedStatement stmt, int index, Object value, int unidbType)
        throws SQLException {
    // Derby needs special handling.
    boolean isDerby = (stmt instanceof DelegatingPreparedStatement)
            ? ((DelegatingPreparedStatement) stmt).getDelegate().getClass().getName().contains("derby")
            : stmt.getClass().getName().contains("derby");
    if (value == null) {
        if (isDerby) {
            if (unidbType == NCHAR) {
                stmt.setNull(index, Datatypes.getSQLType(CHAR));
            } else if (unidbType == NVARCHAR) {
                stmt.setNull(index, Datatypes.getSQLType(VARCHAR));
            } else {
                stmt.setNull(index, Datatypes.getSQLType(unidbType));
            }
        } else {
            stmt.setNull(index, Datatypes.getSQLType(unidbType));
        }
    } else {
        try {
            switch (unidbType) {
            case BOOLEAN:
                stmt.setByte(index, (byte) (((Number) value).intValue() == 1 ? 1 : 0));
                break;
            case TINYINT:
                stmt.setByte(index, ((Number) value).byteValue());
                break;
            case SMALLINT:
                stmt.setShort(index, ((Number) value).shortValue());
                break;
            case INTEGER:
                stmt.setInt(index, ((Number) value).intValue());
                break;
            case BIGINT:
                stmt.setLong(index, ((Number) value).longValue());
                break;
            case DECIMAL:
                stmt.setBigDecimal(index, ((BigDecimal) value));
                break;
            case REAL:
                stmt.setFloat(index, ((Float) value).floatValue());
                break;
            case DOUBLE:
                stmt.setDouble(index, ((Double) value).doubleValue());
                break;
            case CHAR:
                stmt.setString(index, (String) value);
                break;
            case NCHAR:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value);
                }
                break;
            case VARCHAR:
                stmt.setString(index, (String) value);
                break;
            case NVARCHAR:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value);
                }
                break;
            case CLOB: // Clob/NClob can be represented as String without any problem. - Oct 16, 2008.
                stmt.setString(index, (String) value); // stmt.setClob(index, ((Clob) value));
                break;
            case NCLOB:
                if (isDerby) {
                    stmt.setString(index, (String) value);
                } else {
                    stmt.setNString(index, (String) value); // stmt.setNClob(index, ((NClob) value));
                }
                break;
            case BLOB:
                stmt.setBlob(index, ((Blob) value));
                break;
            case TIMESTAMP:
                stmt.setTimestamp(index, ((Timestamp) value));
                break;
            default:
                throw new IllegalArgumentException("[!NO SUCH UNIDB DATA TYPE: " + unidbType + "]");
            }
        } catch (ClassCastException cce) {
            throw new SQLException(
                    "Failed to convert " + value + " (" + value.getClass() + ") to " + getName(unidbType));
        }
    }
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLJDBC.java

public int storeData(DataList list) {
    try {/*w w  w  .j a  va  2 s  .c  o m*/
        Connection conn = dataSourceWrite.getConnection();
        if (conn != null) {
            int i;
            DataItem item;
            EventItem event;
            Object tag;

            conn.setAutoCommit(false);
            PreparedStatement stmt;

            Date t1 = new Date();

            stmt = conn.prepareStatement(sqlInsertStmt);
            for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                if (!(item instanceof EventItem))
                    continue;
                event = (EventItem) item;
                ValueItem val = event.getValue();

                tag = this.getTagOfDp(event.getDp());
                if (tag == null)
                    continue;

                if (tag instanceof Long)
                    stmt.setLong(1, (Long) tag);
                else if (tag instanceof String)
                    stmt.setString(1, (String) tag);

                java.sql.Timestamp ts = new java.sql.Timestamp(event.getTimeMS());
                ts.setNanos(event.getNanos());

                stmt.setTimestamp(2, ts, cal);

                Double dval = val.getDouble();
                if (dval != null) {
                    stmt.setDouble(3, dval);
                } else {
                    stmt.setNull(3, Types.DOUBLE);
                }

                // value_string                    
                stmt.setString(4, val.getString());

                // value_timestamp
                if (val.getTimeMS() != null)
                    stmt.setTimestamp(5, new java.sql.Timestamp(val.getTimeMS()), cal);
                else
                    stmt.setNull(5, Types.TIMESTAMP);

                // status, manager, user
                if (event.hasAttributes()) {
                    stmt.setLong(6, event.getStatus());
                    stmt.setInt(7, event.getManager());
                    stmt.setInt(8, event.getUser());
                } else {
                    stmt.setNull(6, Types.INTEGER);
                    stmt.setNull(7, Types.INTEGER);
                    stmt.setNull(8, Types.INTEGER);
                }

                //JDebug.out.log(Level.FINE, "{0}:{1}/{2} [{3}]", new Object[] {i, element_id.toString(), ts.toString(), item.toString()});

                stmt.addBatch();
            }
            try {
                stmt.executeBatch(); // TODO check result? int[] res =
            } catch (BatchUpdateException ex) {
                JDebug.out.log(Level.SEVERE, "Batch exception {0} update count {1}.",
                        new Object[] { ex.getErrorCode(), ex.getUpdateCounts().length });
                JDebug.StackTrace(Level.SEVERE, ex);
            } catch (SQLException ex) {
                SQLException current = ex;
                do {
                    JDebug.out.log(Level.SEVERE, "SQL exception {0}.", new Object[] { ex.getErrorCode() });
                    JDebug.StackTrace(Level.SEVERE, current);
                } while ((current = current.getNextException()) != null);
                //                    for (i = 0; i <= list.getHighWaterMark() && (item = list.getItem(i)) != null; i++) {
                //                        JDebug.out.log(Level.INFO, "{0}", item.toJSONObject());
                //                    }
            }
            Date t2 = new Date();
            stmt.close();

            afterInsert(conn);

            conn.commit();
            conn.close();
            addServerStats(list.getHighWaterMark(), t2.getTime() - t1.getTime());
            return INoSQLInterface.OK;
        } else {
            JDebug.StackTrace(Level.SEVERE, "no connection!");
            return INoSQLInterface.ERR_REPEATABLE;
        }
    } catch (Exception ex) {
        JDebug.StackTrace(Level.SEVERE, ex);
        return INoSQLInterface.ERR_REPEATABLE;
    }
}

From source file:org.wso2.carbon.device.mgt.core.search.mgt.impl.ProcessorImpl.java

private List<Device> searchDeviceDetailsTable(QueryHolder queryHolder) throws SearchDAOException {
    if (log.isDebugEnabled()) {
        log.debug("Query : " + queryHolder.getQuery());
    }// www.j ava  2 s . c  o  m
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    List<Device> devices = new ArrayList<>();
    Map<Integer, Integer> devs = new HashMap<>();
    try {
        conn = this.getConnection();
        stmt = conn.prepareStatement(queryHolder.getQuery());

        int x = 1;
        ValueType[] types = queryHolder.getTypes();
        for (ValueType type : types) {
            if (type.getColumnType().equals(ValueType.columnType.STRING)) {
                stmt.setString(x, type.getStringValue());
                x++;
            } else if (type.getColumnType().equals(ValueType.columnType.INTEGER)) {
                stmt.setInt(x, type.getIntValue());
                x++;
            } else if (type.getColumnType().equals(ValueType.columnType.LONG)) {
                stmt.setLong(x, type.getLongValue());
                x++;
            } else if (type.getColumnType().equals(ValueType.columnType.DOUBLE)) {
                stmt.setDouble(x, type.getDoubleValue());
                x++;
            }
        }

        rs = stmt.executeQuery();
        while (rs.next()) {
            if (!devs.containsKey(rs.getInt("ID"))) {
                Device device = new Device();
                device.setId(rs.getInt("ID"));
                device.setDescription(rs.getString("DESCRIPTION"));
                device.setName(rs.getString("NAME"));
                device.setType(rs.getString("DEVICE_TYPE_NAME"));
                device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));

                EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
                enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("DE_STATUS")));
                enrolmentInfo.setOwner(rs.getString("OWNER"));
                enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
                device.setEnrolmentInfo(enrolmentInfo);

                DeviceIdentifier identifier = new DeviceIdentifier();
                identifier.setType(rs.getString("DEVICE_TYPE_NAME"));
                identifier.setId(rs.getString("DEVICE_IDENTIFICATION"));

                DeviceInfo deviceInfo = new DeviceInfo();
                deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY"));
                deviceInfo.setBatteryLevel(rs.getDouble("BATTERY_LEVEL"));
                deviceInfo.setConnectionType(rs.getString("CONNECTION_TYPE"));
                deviceInfo.setCpuUsage(rs.getDouble("CPU_USAGE"));
                deviceInfo.setDeviceModel(rs.getString("DEVICE_MODEL"));
                deviceInfo.setExternalAvailableMemory(rs.getDouble("EXTERNAL_AVAILABLE_MEMORY"));
                deviceInfo.setExternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY"));
                deviceInfo.setInternalAvailableMemory(rs.getDouble("INTERNAL_AVAILABLE_MEMORY"));
                deviceInfo.setInternalTotalMemory(rs.getDouble("EXTERNAL_TOTAL_MEMORY"));
                deviceInfo.setOsVersion(rs.getString("OS_VERSION"));
                deviceInfo.setOsBuildDate(rs.getString("OS_BUILD_DATE"));
                deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN"));
                deviceInfo.setSsid(rs.getString("SSID"));
                deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY"));
                deviceInfo.setVendor(rs.getString("VENDOR"));
                deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP")));

                DeviceLocation deviceLocation = new DeviceLocation();
                deviceLocation.setLatitude(rs.getDouble("LATITUDE"));
                deviceLocation.setLongitude(rs.getDouble("LONGITUDE"));
                deviceLocation.setStreet1(rs.getString("STREET1"));
                deviceLocation.setStreet2(rs.getString("STREET2"));
                deviceLocation.setCity(rs.getString("CITY"));
                deviceLocation.setState(rs.getString("STATE"));
                deviceLocation.setZip(rs.getString("ZIP"));
                deviceLocation.setCountry(rs.getString("COUNTRY"));
                deviceLocation.setDeviceId(rs.getInt("ID"));
                deviceLocation.setUpdatedTime(new java.util.Date(rs.getLong("DL_UPDATED_TIMESTAMP")));

                deviceInfo.setLocation(deviceLocation);
                device.setDeviceInfo(deviceInfo);
                devices.add(device);
                devs.put(device.getId(), device.getId());
            }
        }
    } catch (SQLException e) {
        throw new SearchDAOException("Error occurred while aquiring the device details.", e);
    } finally {
        DeviceManagementDAOUtil.cleanupResources(stmt, rs);
    }
    this.fillPropertiesOfDevices(devices);
    if (log.isDebugEnabled()) {
        log.debug("Number of the device returned from the query : " + devices.size());
    }
    return devices;
}