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.xenei.bloomgraph.bloom.sql.MySQLCommands.java

@Override
public PreparedStatement tripleSearch(final Connection connection, final int pageId,
        final PageSearchItem candidate) throws SQLException, IOException {
    String sql = null;/*from   ww  w.  ja  v a 2 s .  c o  m*/
    PreparedStatement stmt = null;
    try {
        if (candidate.getSerializable().containsWild()) {
            sql = String.format(
                    "SELECT data, idx FROM Page_%s WHERE hamming>=? AND log>=? AND bloommatch( ?, bloom)",
                    pageId);
            stmt = connection.prepareStatement(sql);
            stmt.setInt(1, candidate.getTripleFilter().getHammingWeight());
            stmt.setDouble(2, candidate.getTripleFilter().getApproximateLog(APPROX_LOG_DEPTH));
            stmt.setBlob(3, DBIO.asInputStream(candidate.getTripleFilter().getByteBuffer()));
        } else {
            sql = String.format("SELECT data, idx FROM Page_%s WHERE hash=?", pageId);
            stmt = connection.prepareStatement(sql);
            stmt.setInt(1, candidate.getTriple().hashCode());
        }
        LOG.debug("Checking {} with {}", candidate.getTriple(), stmt);
        return stmt;
    } catch (final SQLException e) {
        DbUtils.closeQuietly(stmt);
        throw e;
    } catch (final IOException e) {
        DbUtils.closeQuietly(stmt);
        throw e;
    }
}

From source file:uta.ak.usttmp.dmcore.service.impl.MiningTaskServiceImpl.java

protected long doCreateSingleMiningTask(MiningTask mt) {

    if (checkDuplTask(mt.getName())) {
        throw new IllegalArgumentException("The name of mining task is duplicated.");
    }/* w  w  w . ja v  a  2s  . c o m*/

    final String insertSql = "INSERT INTO `c_miningtask` ( " + "   `name`, " + "   `starttime`, "
            + "   `endtime`, " + "   `mininginterval`, " + "   `status`, " + "   `tag`, "
            + "   `qrtz_job_exec_count`, " + "   `qrtz_job_total_count`," + "   `topic_num`,"
            + "   `keyword_num`," + "   `alpha`," + "   `beta`," + "   `preprocess_component`,"
            + "   `mining_component`," + "   `tracking_component`" + ") " + "VALUES " + "   ( " + "      ?, "
            + "      ?, " + "      ?, " + "      ?, " + "      ?, " + "      ?, " + "      ?, " + "      ?, "
            + "      ?, " + "      ?, " + "      ?, " + "      ?, " + "      ?, " + "      ?, " + "      ? )";

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    KeyHolder keyHolder = new GeneratedKeyHolder();
    JdbcTemplate jt = this.getJdbcTemplate();

    jt.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement pst = con.prepareStatement(insertSql, new String[] { "mme_eid" });
            pst.setString(1, mt.getName());
            pst.setString(2, formatter.format(mt.getStartTime()));
            pst.setString(3, formatter.format(mt.getEndTime()));
            pst.setInt(4, mt.getMiningInterval());
            pst.setInt(5, MiningTask.STATUS_NOT_STARTED);
            pst.setString(6, mt.getTag());
            pst.setInt(7, 0);
            pst.setInt(8, mt.getQrtzJobTotalCount());
            pst.setInt(9, mt.getTopicNum());
            pst.setInt(10, mt.getKeywordNum());
            pst.setDouble(11, mt.getAlpha());
            pst.setDouble(12, mt.getBeta());
            pst.setString(13, mt.getPreprocessComponent());
            pst.setString(14, mt.getMiningComponent());
            pst.setString(15, mt.getTrackingComponent());
            return pst;
        }
    }, keyHolder);

    long taskId = (long) keyHolder.getKey();

    return taskId;
}

From source file:com.enigmastation.ml.perceptron.impl.HSQLDBPerceptronRepository.java

@Override
public void setStrength(int from, int to, Layer layer, double strength) {
    PreparedStatement ps;
    ResultSet rs;/* w  w w .j  a va2  s. co m*/
    try (Connection conn = getConnection()) {
        ps = conn.prepareStatement("select id from " + layer.getStoreName() + " where fromid=? and toid=?");
        ps.setInt(1, from);
        ps.setInt(2, to);
        rs = ps.executeQuery();
        if (rs.next()) {
            // update
            int id = rs.getInt(1);
            rs.close();
            ps.close();
            ps = conn.prepareStatement("update " + layer.getStoreName() + " set strength=? where id=?");
            ps.setDouble(1, strength);
            ps.setInt(2, id);
            ps.executeUpdate();
        } else {
            rs.close();
            ps.close();
            // insert
            ps = conn.prepareStatement(
                    "insert into " + layer.getStoreName() + " (fromid, toid, strength) " + " values (?, ?, ?)");
            ps.setInt(1, from);
            ps.setInt(2, to);
            ps.setDouble(3, strength);
            ps.executeUpdate();
        }
        ps.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.schedoscope.export.jdbc.outputformat.JdbcOutputWritable.java

@Override
public void write(PreparedStatement ps) throws SQLException {

    List<Pair<String, String>> record = fromArrayWritable(value);
    try {/*from   ww w . j  a v a  2  s  .  c om*/
        for (int i = 0; i < record.size(); i++) {

            String type = record.get(i).getLeft().toLowerCase(Locale.getDefault());

            if (type.equals(JdbcOutputWritable.STRING)) {
                if (!record.get(i).getRight().equals("NULL")) {
                    ps.setString(i + 1, record.get(i).getRight());
                } else {
                    ps.setNull(i + 1, Types.VARCHAR);
                }

            } else if (type.equals(JdbcOutputWritable.DOUBLE)) {
                if (!record.get(i).getRight().equals("NULL")) {
                    ps.setDouble(i + 1, Double.parseDouble(record.get(i).getRight()));
                } else {
                    ps.setNull(i + 1, Types.DOUBLE);
                }
            } else if (type.equals(JdbcOutputWritable.BOOLEAN)) {
                if (!record.get(i).getRight().equals("NULL")) {
                    ps.setBoolean(i + 1, Boolean.parseBoolean(record.get(i).getRight()));
                } else {
                    ps.setNull(i + 1, Types.BOOLEAN);
                }
            } else if (type.equals(JdbcOutputWritable.INTEGER)) {
                if (!record.get(i).getRight().equals("NULL")) {
                    ps.setInt(i + 1, Integer.parseInt(record.get(i).getRight()));
                } else {
                    ps.setNull(i + 1, Types.INTEGER);
                }
            } else if (type.equals(JdbcOutputWritable.LONG)) {
                if (!record.get(i).getRight().equals("NULL")) {
                    ps.setLong(i + 1, Long.parseLong(record.get(i).getRight()));
                } else {
                    ps.setNull(i + 1, Types.BIGINT);
                }

            } else {
                LOG.warn("Unknown column type: " + record.get(i).getLeft().toLowerCase(Locale.getDefault()));
                ps.setString(i + 1, record.get(i).getRight());
            }
        }
    } catch (NumberFormatException n) {
        n.printStackTrace();
    }
}

From source file:lineage2.loginserver.accounts.Account.java

/**
 * Method update./*from   ww  w . j  a  v  a 2  s  .  co m*/
 */
public void update() {
    Connection con = null;
    PreparedStatement statement = null;
    try {
        con = L2DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement(
                "UPDATE accounts SET password = ?, access_level = ?, ban_expire = ?, allow_ip = ?, bonus = ?, bonus_expire = ?, last_server = ?, last_ip = ?, last_access = ? WHERE login = ?");
        statement.setString(1, getPasswordHash());
        statement.setInt(2, getAccessLevel());
        statement.setInt(3, getBanExpire());
        statement.setString(4, getAllowedIP());
        statement.setDouble(5, getBonus());
        statement.setInt(6, getBonusExpire());
        statement.setInt(7, getLastServer());
        statement.setString(8, getLastIP());
        statement.setInt(9, getLastAccess());
        statement.setString(10, getLogin());
        statement.execute();
    } catch (Exception e) {
        _log.error("", e);
    } finally {
        DbUtils.closeQuietly(con, statement);
    }
}

From source file:uk.ac.cam.cl.dtg.segue.dos.PgLocationHistory.java

@Override
public void storePostCodes(List<PostCode> foundPostCodes) throws SegueDatabaseException {
    PreparedStatement pst;
    try (Connection conn = database.getDatabaseConnection()) {
        conn.setAutoCommit(false);//from  w  w w. ja  va 2s .c  o  m

        for (PostCode postCode : foundPostCodes) {

            // Ignore post codes with invalid lat/lon
            if (postCode.getLat() == null || postCode.getLon() == null) {
                continue;
            }

            pst = conn.prepareStatement(
                    "INSERT INTO uk_post_codes " + "(postcode, lat, lon) " + "VALUES (?, ?, ?)");

            pst.setString(1, postCode.getPostCode());
            pst.setDouble(2, postCode.getLat());
            pst.setDouble(3, postCode.getLon());

            if (pst.executeUpdate() == 0) {
                throw new SegueDatabaseException("Unable to save location event.");
            }
        }
        conn.commit();
        conn.setAutoCommit(true);

    } catch (SQLException e) {
        throw new SegueDatabaseException("Postgres exception", e);
    }
}

From source file:chh.utils.db.source.common.JdbcClient.java

private void setPreparedStatementParams(PreparedStatement preparedStatement, List<Column> columnList)
        throws SQLException {
    int index = 1;
    for (Column column : columnList) {
        Class columnJavaType = Util.getJavaType(column.getSqlType());
        if (column.getVal() == null) {
            preparedStatement.setNull(index, column.getSqlType());
        } else if (columnJavaType.equals(String.class)) {
            preparedStatement.setString(index, (String) column.getVal());
        } else if (columnJavaType.equals(Integer.class)) {
            preparedStatement.setInt(index, (Integer) column.getVal());
        } else if (columnJavaType.equals(Double.class)) {
            preparedStatement.setDouble(index, (Double) column.getVal());
        } else if (columnJavaType.equals(Float.class)) {
            preparedStatement.setFloat(index, (Float) column.getVal());
        } else if (columnJavaType.equals(Short.class)) {
            preparedStatement.setShort(index, (Short) column.getVal());
        } else if (columnJavaType.equals(Boolean.class)) {
            preparedStatement.setBoolean(index, (Boolean) column.getVal());
        } else if (columnJavaType.equals(byte[].class)) {
            preparedStatement.setBytes(index, (byte[]) column.getVal());
        } else if (columnJavaType.equals(Long.class)) {
            preparedStatement.setLong(index, (Long) column.getVal());
        } else if (columnJavaType.equals(Date.class)) {
            preparedStatement.setDate(index, (Date) column.getVal());
        } else if (columnJavaType.equals(Time.class)) {
            preparedStatement.setTime(index, (Time) column.getVal());
        } else if (columnJavaType.equals(Timestamp.class)) {
            preparedStatement.setTimestamp(index, (Timestamp) column.getVal());
        } else {/*  w ww .  j  a va  2 s  .com*/
            throw new RuntimeException(
                    "Unknown type of value " + column.getVal() + " for column " + column.getColumnName());
        }
        ++index;
    }
}

From source file:org.wso2.carbon.ml.model.internal.DatabaseHandler.java

/**
 * This method inserts model settings to database
 *
 * @param modelSettingsID   Model settings ID
 * @param workflowID        Workflow ID/*from w w  w  . ja  v a2s  .c  o  m*/
 * @param algorithmName     Machine learning algorithm name
 * @param algorithmClass    Type of machine learning algorithm: e.g. Classification
 * @param response          Name of the response variable
 * @param trainDataFraction Training data fraction
 * @param hyperparameters   Hyper-parameters
 * @throws DatabaseHandlerException
 */
public void insertModelSettings(String modelSettingsID, String workflowID, String algorithmName,
        String algorithmClass, String response, double trainDataFraction, List<HyperParameter> hyperparameters)
        throws DatabaseHandlerException {
    Connection connection = null;
    PreparedStatement insertStatement = null;
    try {
        // insert model settings to the database.
        connection = this.dataSource.getConnection();
        connection.setAutoCommit(false);
        insertStatement = connection.prepareStatement(SQLQueries.INSERT_ML_MODEL_SETTINGS);
        insertStatement.setString(1, modelSettingsID);
        insertStatement.setString(2, workflowID);
        insertStatement.setString(3, algorithmName);
        insertStatement.setString(4, algorithmClass);
        insertStatement.setString(5, response);
        insertStatement.setDouble(6, trainDataFraction);
        insertStatement.setObject(7, hyperparameters);
        insertStatement.execute();
        connection.commit();
        if (logger.isDebugEnabled()) {
            logger.debug("Succesfully updated model settings for model settings id " + modelSettingsID);
        }
    } catch (SQLException e) {
        // rollback the changes.
        MLDatabaseUtils.rollBack(connection);
        throw new DatabaseHandlerException(
                "An error occured while inserting model settings for model settings id " + modelSettingsID
                        + " to the database: " + e.getMessage(),
                e);
    } finally {
        // enable auto commit.
        MLDatabaseUtils.enableAutoCommit(connection);
        // close the database resources.
        MLDatabaseUtils.closeDatabaseResources(connection, insertStatement);
    }
}

From source file:oscar.util.SqlUtils.java

/**
 * this utility-method assigns a particular value to a place holder of a PreparedStatement. it tries to find the correct setXxx() value, accoring to the field-type information
 * represented by "fieldType". quality: this method is bloody alpha (as you migth see :=)
 *//*from ww  w.j  a v a  2 s.  c  om*/
public static void fillPreparedStatement(PreparedStatement ps, int col, Object val, int fieldType)
        throws SQLException {
    try {
        logger.info("fillPreparedStatement( ps, " + col + ", " + val + ", " + fieldType + ")...");
        Object value = null;
        // Check for hard-coded NULL
        if (!("$null$".equals(val))) {
            value = val;
        }
        if (value != null) {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setInt(col, Integer.parseInt((String) value));
                break;
            case FieldTypes.NUMERIC:
                ps.setBigDecimal(col, createAppropriateNumeric(value));
                break;
            case FieldTypes.CHAR:
                ps.setString(col, (String) value);
                break;
            case FieldTypes.DATE:
                ps.setDate(col, createAppropriateDate(value));
                break; // #checkme
            case FieldTypes.TIMESTAMP:
                ps.setTimestamp(col, java.sql.Timestamp.valueOf((String) value));
                break;
            case FieldTypes.DOUBLE:
                ps.setDouble(col, Double.valueOf((String) value).doubleValue());
                break;
            case FieldTypes.FLOAT:
                ps.setFloat(col, Float.valueOf((String) value).floatValue());
                break;
            case FieldTypes.LONG:
                ps.setLong(col, Long.parseLong(String.valueOf(value)));
                break;
            case FieldTypes.BLOB:
                FileHolder fileHolder = (FileHolder) value;
                try {
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(byteOut);
                    out.writeObject(fileHolder);
                    out.flush();
                    byte[] buf = byteOut.toByteArray();
                    byteOut.close();
                    out.close();
                    ByteArrayInputStream bytein = new ByteArrayInputStream(buf);
                    int byteLength = buf.length;
                    ps.setBinaryStream(col, bytein, byteLength);
                    // store fileHolder as a whole (this way we don't lose file meta-info!)
                } catch (IOException ioe) {
                    MiscUtils.getLogger().error("Error", ioe);
                    logger.info(ioe.toString());
                    throw new SQLException("error storing BLOB in database - " + ioe.toString(), null, 2);
                }
                break;
            case FieldTypes.DISKBLOB:
                ps.setString(col, (String) value);
                break;
            default:
                ps.setObject(col, value); // #checkme
            }
        } else {
            switch (fieldType) {
            case FieldTypes.INTEGER:
                ps.setNull(col, java.sql.Types.INTEGER);
                break;
            case FieldTypes.NUMERIC:
                ps.setNull(col, java.sql.Types.NUMERIC);
                break;
            case FieldTypes.CHAR:
                ps.setNull(col, java.sql.Types.CHAR);
                break;
            case FieldTypes.DATE:
                ps.setNull(col, java.sql.Types.DATE);
                break;
            case FieldTypes.TIMESTAMP:
                ps.setNull(col, java.sql.Types.TIMESTAMP);
                break;
            case FieldTypes.DOUBLE:
                ps.setNull(col, java.sql.Types.DOUBLE);
                break;
            case FieldTypes.FLOAT:
                ps.setNull(col, java.sql.Types.FLOAT);
                break;
            case FieldTypes.BLOB:
                ps.setNull(col, java.sql.Types.BLOB);
            case FieldTypes.DISKBLOB:
                ps.setNull(col, java.sql.Types.CHAR);
            default:
                ps.setNull(col, java.sql.Types.OTHER);
            }
        }
    } catch (Exception e) {
        throw new SQLException("Field type seems to be incorrect - " + e.toString(), null, 1);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.jdbc.dialect.DialectDB2.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;//w w  w  . j  a v  a2 s .c o m
    case Types.BIT:
        ps.setInt(index, ((Boolean) value).booleanValue() ? 1 : 0);
        return;
    case Types.TINYINT:
    case Types.SMALLINT:
        ps.setInt(index, ((Long) value).intValue());
        return;
    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());
    }
}