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:no.polaric.aprsdb.MyDBSession.java

/**
 * Get points that were transmitted via a certain digipeater during a certain time span. 
 *//*from  w  ww  .ja  v a2 s .  c o  m*/
public DbList<TPoint> getPointsVia(String digi, Reference uleft, Reference lright, java.util.Date from,
        java.util.Date to) throws java.sql.SQLException {
    _log.debug("MyDbSession", "getPointsVia: " + digi + ", " + df.format(from) + " - " + df.format(to));
    PreparedStatement stmt = getCon().prepareStatement(
            " SELECT DISTINCT position " + " FROM \"AprsPacket\" p, \"PosReport\" r " + " WHERE  p.src=r.src "
                    + " AND  p.time=r.rtime " + " AND  (substring(p.path, '([^,\\*]+).*\\*.*')=? OR "
                    + " (substring(p.ipath, 'qAR,([^,\\*]+).*')=? AND p.path !~ '.*\\*.*')) "
                    + " AND  position && ST_MakeEnvelope(?, ?, ?, ?, 4326) "
                    + " AND  p.time > ? AND p.time < ? LIMIT 10000",

            ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    stmt.setString(1, digi);
    stmt.setString(2, digi);

    LatLng ul = uleft.toLatLng();
    LatLng lr = lright.toLatLng();
    stmt.setDouble(3, ul.getLng());
    stmt.setDouble(4, ul.getLat());
    stmt.setDouble(5, lr.getLng());
    stmt.setDouble(6, lr.getLat());

    stmt.setTimestamp(7, date2ts(from));
    stmt.setTimestamp(8, date2ts(to));
    stmt.setMaxRows(10000);

    return new DbList(stmt.executeQuery(), rs -> {
        return new TPoint(null, getRef(rs, "position"));
    });
}

From source file:de.ingrid.importer.udk.strategy.v30.IDCStrategy3_0_0_fixErfassungsgrad.java

private void fixErfassungsgrad() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Fix \"Erfassungsgrad\" (t011_obj_geo.rec_grade) from Commission to Omission...");
    }//from  ww  w .  ja  v a  2 s.c  om

    // sql
    String sql = "select * from t011_obj_geo where rec_grade IS NOT NULL";

    PreparedStatement pS = jdbc.prepareStatement("UPDATE t011_obj_geo SET rec_grade = ? where id = ?");
    Statement st = jdbc.createStatement();
    ResultSet rs = jdbc.executeQuery(sql, st);
    int numFixed = 0;
    while (rs.next()) {
        long id = rs.getLong("id");
        long objId = rs.getLong("obj_id");
        double oldRecGrade = rs.getDouble("rec_grade");
        double newRecGrade = 100.0 - oldRecGrade;
        if (newRecGrade < 0.0) {
            newRecGrade = 0.0;
            log.warn("New value " + newRecGrade + " < 0, we set new value to 0.0.");
        }
        if (newRecGrade > 100.0) {
            newRecGrade = 100.0;
            log.warn("New value " + newRecGrade + " > 100, we set new value to 100.0.");
        }

        try {
            // round 2 decimals after digit
            newRecGrade = new BigDecimal(newRecGrade).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception ex) {
            log.error("Problems rounding " + newRecGrade
                    + " to 2 decimals after digit, we keep unrounded value." + ex);
        }

        pS.setDouble(1, newRecGrade);
        pS.setLong(2, id);
        int numUpdated = pS.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Fixed t011_obj_geo.rec_grade from " + oldRecGrade + " to " + newRecGrade + " ("
                    + numUpdated + " row(s), objectId: " + objId + ")");
        }
        numFixed++;
    }

    pS.close();
    rs.close();
    st.close();

    if (log.isInfoEnabled()) {
        log.info("Fixed " + numFixed + " times \"Erfassungsgrad\"");
    }

    if (log.isInfoEnabled()) {
        log.info("Fix \"Erfassungsgrad\" (t011_obj_geo.rec_grade) from Commission to Omission...done");
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectSQLServer.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;/*from   ww  w.ja  va2s  .c  o m*/
    case Types.BIT:
        ps.setBoolean(index, ((Boolean) value).booleanValue());
        return;
    case Types.TINYINT:
    case Types.INTEGER:
    case Types.BIGINT:
        ps.setLong(index, ((Number) value).longValue());
        return;
    case Types.DOUBLE:
        ps.setDouble(index, ((Double) value).doubleValue());
        return;
    case Types.TIMESTAMP:
        setToPreparedStatementTimestamp(ps, index, value, column);
        return;
    default:
        throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
    }
}

From source file:br.com.cobranca.util.Util.java

public static <T> int inserirRegistro(T obj, Connection con) throws Exception {

    int id = 0;//w  ww . j av a2s.  c  o  m

    String nomeTabela = obj.getClass().getSimpleName();

    String strSql = "INSERT INTO " + nomeTabela.toUpperCase() + " (";
    boolean usarVirgula = false;

    for (Field field : obj.getClass().getDeclaredFields()) {
        field.setAccessible(true);

        if (usarVirgula) {
            strSql = strSql + ", ";
        }

        strSql = strSql + field.getName();

        if (!usarVirgula) {
            usarVirgula = true;
        }
    }

    strSql = strSql + ") VALUES (";

    usarVirgula = false;

    for (Field field : obj.getClass().getDeclaredFields()) {
        field.setAccessible(true);

        if (usarVirgula) {
            strSql = strSql + ", ";
        }

        strSql = strSql + "?";

        if (!usarVirgula) {
            usarVirgula = true;
        }
    }

    strSql = strSql + ")";

    PreparedStatement ps = con.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS);

    try {

        int i = 1;
        for (Field field : obj.getClass().getDeclaredFields()) {

            String tipoColuna = field.getType().getSimpleName();

            if (tipoColuna.toUpperCase().contains("INT")) {
                tipoColuna = "Int";
            } else {
                tipoColuna = StringPrimeiraLetraMaiuscula(tipoColuna);
            }

            // obj . get + nome do campo
            Method met = obj.getClass().getMethod("get" + StringPrimeiraLetraMaiuscula(field.getName()));

            if (tipoColuna.equals("Int")) {

                Integer valor = (Integer) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setInt(i, valor);
                }

            } else if (tipoColuna.equals("String")) {
                String valor = (String) met.invoke(obj);
                ps.setString(i, valor);
            } else if (tipoColuna.equals("Double")) {

                Double valor = (Double) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setDouble(i, valor);
                }

            } else if (tipoColuna.equals("Float")) {

                Float valor = (Float) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setFloat(i, valor);
                }

            } else if (tipoColuna.equals("Long")) {

                Long valor = (Long) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setLong(i, valor);
                }

            } else if (tipoColuna.equals("Boolean")) {
                Boolean valor = (Boolean) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setBoolean(i, valor);
                }

            } else if (tipoColuna.equals("Date")) {
                Date valor = (Date) met.invoke(obj);

                if (valor == null) {
                    ps.setString(i, null);
                } else {
                    ps.setDate(i, new java.sql.Date(valor.getTime()));
                }

            } else {
                return 0;
            }

            i++;
        }

        int qtdLinhasAfetadas = ps.executeUpdate();

        if (qtdLinhasAfetadas > 0) {

            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    id = rs.getInt(1);
                }
            }

        }
    } catch (Exception ex) {
        throw new Exception(ex.getMessage());
    } finally {
        ps.close();
    }

    return id;
}

From source file:gov.nih.nci.cadsr.persist.de.Data_Elements_Mgr.java

/**
 * Inserts a single row of Data Element in data_elements_view table and returns primary key de_IDSEQ
 * /*ww w . j av  a 2 s  .c o m*/
 * @param deVO
 * @param conn
 * @return
 * @throws DBException
 */
public String insert(BaseVO vo, Connection conn) throws DBException {
    DeVO deVO = (DeVO) vo;
    PreparedStatement statement = null;
    String primaryKey = null;
    // generate de_IDSEQ(primary key) 
    deVO.setDe_IDSEQ(this.generatePrimaryKey(conn));
    deVO.setDeleted_ind(DBConstants.RECORD_DELETED_NO);
    deVO.setDate_created(new java.sql.Timestamp(new java.util.Date().getTime()));
    try {
        String sql = "insert into data_elements_view ( de_idseq, version, conte_idseq, preferred_name, vd_idseq, dec_idseq, "
                + "preferred_definition, asl_name, long_name, latest_version_ind, deleted_ind, "
                + "date_created, begin_date, created_by, end_date, date_modified, modified_by, change_note, origin) "
                + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        int column = 0;
        statement = conn.prepareStatement(sql);
        statement.setString(++column, deVO.getDe_IDSEQ());
        statement.setDouble(++column, deVO.getVersion());
        statement.setString(++column, deVO.getConte_IDSEQ());
        statement.setString(++column, deVO.getPrefferred_name());
        statement.setString(++column, deVO.getVd_IDSEQ());
        statement.setString(++column, deVO.getDec_IDSEQ());
        statement.setString(++column, deVO.getPrefferred_def());
        statement.setString(++column, deVO.getAsl_name());
        statement.setString(++column, deVO.getLong_name());
        statement.setString(++column, deVO.getLastest_version_ind());
        statement.setString(++column, deVO.getDeleted_ind());
        statement.setTimestamp(++column, deVO.getDate_created());
        statement.setTimestamp(++column, deVO.getBegin_date());
        statement.setString(++column, deVO.getCreated_by());
        statement.setTimestamp(++column, deVO.getEnd_date());
        statement.setTimestamp(++column, deVO.getDate_modified());
        statement.setString(++column, deVO.getModified_by());
        statement.setString(++column, deVO.getChange_note());
        statement.setString(++column, deVO.getOrigin());

        int count = statement.executeUpdate();
        if (count == 0) {
            throw new Exception("Unable to insert the record");
        } else {
            primaryKey = deVO.getDe_IDSEQ();
            if (logger.isDebugEnabled()) {
                logger.debug("Inserted DE");
                logger.debug("de_IDSEQ(primary key )-----> " + primaryKey);
            }
        }

    } catch (Exception e) {
        logger.error("Error inserting Data Element " + e);
        errorList.add(DeErrorCodes.API_DE_500);
        throw new DBException(errorList);
    } finally {
        statement = SQLHelper.closePreparedStatement(statement);
    }
    return primaryKey;
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateBugGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) {
    if (CollectionUtils.isNotEmpty(taskGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-bug-service" + sAccountId);
        try {// w ww  . j  av  a  2s.com
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement batchTasksStatement = connection.prepareStatement(
                            "UPDATE `m_tracker_bug` SET " + "summary = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignuser`=?, `ganttindex`=?, "
                                    + "`milestoneId`=? WHERE `id` = ?");
                    for (int i = 0; i < taskGanttItems.size(); i++) {
                        TaskGanttItem ganttItem = taskGanttItems.get(i);
                        if (ProjectTypeConstants.BUG.equals(ganttItem.getType())) {
                            batchTasksStatement.setString(1, ganttItem.getName());
                            batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate()));
                            batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate()));
                            batchTasksStatement.setDate(4, new Date(now));
                            batchTasksStatement.setDouble(5,
                                    MoreObjects.firstNonNull(ganttItem.getProgress(), 0d));
                            batchTasksStatement.setString(6, ganttItem.getAssignUser());
                            batchTasksStatement.setInt(7, ganttItem.getGanttIndex());
                            batchTasksStatement.setObject(8, ganttItem.getMilestoneId());
                            batchTasksStatement.setInt(9, ganttItem.getId());
                            batchTasksStatement.addBatch();
                        }

                    }
                    batchTasksStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-bug-service" + sAccountId);
            lock.unlock();
        }
    }
}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

public int updateProfile(String notesID, String pemID, String ilID, String techDomain, String techOther,
        double utilization, String location, String onSiteFlag, String onBenchFlag, String regiesteredFlag)
        throws Exception {

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE profile SET ");
    sqlBuilder.append("PeMID = ?, ");
    sqlBuilder.append("ILID = ?, ");
    sqlBuilder.append("TechDomain = ?, ");
    sqlBuilder.append("TechOther = ?, ");
    sqlBuilder.append("Utilization = ?, ");
    sqlBuilder.append("Location = ?, ");
    sqlBuilder.append("OnSiteFlag = ?, ");
    sqlBuilder.append("OnBenchFlag = ?, ");
    sqlBuilder.append("RegiesteredFlag = ? ");
    sqlBuilder.append("WHERE NotesID = ?");

    Connection connection = null;
    PreparedStatement statement = null;
    try {/*from  w ww .  ja  v a 2  s  . c o m*/
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());

        statement.setString(1, pemID);
        statement.setString(2, ilID);
        statement.setString(3, techDomain);
        statement.setString(4, techOther);
        statement.setDouble(5, utilization);
        statement.setString(6, location);
        statement.setString(7, onSiteFlag);
        statement.setString(8, onBenchFlag);
        statement.setString(9, regiesteredFlag);
        statement.setString(10, notesID);

        return statement.executeUpdate();
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }
}

From source file:com.ibm.bluemix.samples.PostgreSQLClient.java

/**
 * Insert text into PostgreSQL/*from  ww  w .ja  v  a  2s . co m*/
 * 
 * param posts List of Strings of text to insert
 * 
 * @return number of rows affected
 * @throws Exception
 * @throws Exception
 */
public int updateTrack(String notesID, String liquidID, String completeDate, String status, String isFirst,
        String isSecond, double winDollar, double winHour, double winPoint) throws Exception {

    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE track SET ");
    sqlBuilder.append("CompleteDate = ?, ");
    sqlBuilder.append("Status = ?, ");
    sqlBuilder.append("IsFirst = ?, ");
    sqlBuilder.append("IsSecond = ?, ");
    sqlBuilder.append("WinDollar = ?, ");
    sqlBuilder.append("WinHour = ?, ");
    sqlBuilder.append("WinPoint = ?, ");
    sqlBuilder.append("AddDate = now() ");
    sqlBuilder.append("WHERE NotesID = ? AND LiquidID = ?");

    Connection connection = null;
    PreparedStatement statement = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(sqlBuilder.toString());

        statement.setString(1, completeDate);
        statement.setString(2, status);
        statement.setString(3, isFirst);
        statement.setString(4, isSecond);
        statement.setDouble(5, winDollar);
        statement.setDouble(6, winHour);
        statement.setDouble(7, winPoint);
        statement.setString(8, notesID);
        statement.setString(9, liquidID);

        return statement.executeUpdate();
    } catch (SQLException e) {
        SQLException next = e.getNextException();

        if (next != null) {
            throw next;
        }

        throw e;
    } finally {
        if (statement != null) {
            statement.close();
        }

        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.apache.hadoop.hive.jdbc.TestJdbcDriver.java

private PreparedStatement createPreapredStatementUsingSetXXX(String sql) throws SQLException {
    PreparedStatement ps = con.prepareStatement(sql);

    ps.setBoolean(1, true); //setBoolean
    ps.setBoolean(2, true); //setBoolean

    ps.setShort(3, Short.valueOf("1")); //setShort
    ps.setInt(4, 2); //setInt
    ps.setFloat(5, 3f); //setFloat
    ps.setDouble(6, Double.valueOf(4)); //setDouble
    ps.setString(7, "test'string\""); //setString
    ps.setLong(8, 5L); //setLong
    ps.setByte(9, (byte) 1); //setByte
    ps.setByte(10, (byte) 1); //setByte
    ps.setString(11, "2012-01-01"); //setString

    ps.setMaxRows(2);/*from   w ww .ja  v  a2 s  .c  o  m*/
    return ps;
}

From source file:com.esofthead.mycollab.module.project.service.ibatis.GanttAssignmentServiceImpl.java

private void massUpdateTaskGanttItems(final List<TaskGanttItem> taskGanttItems, Integer sAccountId) {
    if (CollectionUtils.isNotEmpty(taskGanttItems)) {
        Lock lock = DistributionLockUtil.getLock("gantt-task-service" + sAccountId);
        try {/* w w  w  .  jav a  2 s . c  o  m*/
            final long now = new GregorianCalendar().getTimeInMillis();
            if (lock.tryLock(30, TimeUnit.SECONDS)) {
                try (Connection connection = dataSource.getConnection()) {
                    connection.setAutoCommit(false);
                    PreparedStatement batchTasksStatement = connection.prepareStatement(
                            "UPDATE `m_prj_task` SET " + "taskname = ?, `startdate` = ?, `enddate` = ?, "
                                    + "`lastUpdatedTime`=?, `percentagecomplete`=?, `assignUser`=?, `ganttindex`=?, "
                                    + "`milestoneId`=?, `parentTaskId`=? WHERE `id` = ?");
                    for (int i = 0; i < taskGanttItems.size(); i++) {
                        TaskGanttItem ganttItem = taskGanttItems.get(i);
                        if (ProjectTypeConstants.TASK.equals(ganttItem.getType())) {
                            batchTasksStatement.setString(1, ganttItem.getName());
                            batchTasksStatement.setDate(2, getDateWithNullValue(ganttItem.getStartDate()));
                            batchTasksStatement.setDate(3, getDateWithNullValue(ganttItem.getEndDate()));
                            batchTasksStatement.setDate(4, new Date(now));
                            batchTasksStatement.setDouble(5, ganttItem.getProgress());
                            batchTasksStatement.setString(6, ganttItem.getAssignUser());
                            batchTasksStatement.setInt(7, ganttItem.getGanttIndex());
                            batchTasksStatement.setObject(8, ganttItem.getMilestoneId());
                            batchTasksStatement.setObject(9, ganttItem.getParentTaskId());
                            batchTasksStatement.setInt(10, ganttItem.getId());
                            batchTasksStatement.addBatch();
                        }

                    }
                    batchTasksStatement.executeBatch();
                    connection.commit();
                }
            }
        } catch (Exception e) {
            throw new MyCollabException(e);
        } finally {
            DistributionLockUtil.removeLock("gantt-task-service" + sAccountId);
            lock.unlock();
        }
    }
}