Example usage for java.sql PreparedStatement setFloat

List of usage examples for java.sql PreparedStatement setFloat

Introduction

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

Prototype

void setFloat(int parameterIndex, float x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java float value.

Usage

From source file:com.talkdesk.geo.GeoCodeRepositoryBuilder.java

/**
 * Populate country data for the table ISO and lang / lat mapping
 *
 * @throws GeoResolverException/*from  w  w w .j  ava  2  s .  com*/
 */
public void populateCountryData() throws GeoResolverException {
    try {
        if (connection == null)
            connection = connectToDatabase();

        if (!new File(countryDataLocation).exists()) {
            log.error("No Data file found for countryData. please add to data/country.csv ");
            return;
        }

        Path file = FileSystems.getDefault().getPath(countryDataLocation);
        Charset charset = Charset.forName("UTF-8");
        BufferedReader inputStream = Files.newBufferedReader(file, charset);
        String buffer;
        PreparedStatement preparedStatement;
        preparedStatement = connection.prepareStatement(
                "INSERT INTO countrycodes (COUNTRY_CODE , LATITUDE, LONGITUDE, NAME)" + " VALUES (?,?,?,?)");
        while ((buffer = inputStream.readLine()) != null) {
            String[] values = buffer.split(",");

            preparedStatement.setString(1, values[0].trim());
            preparedStatement.setFloat(2, Float.parseFloat(values[1].trim()));
            preparedStatement.setFloat(3, Float.parseFloat(values[2].trim()));
            preparedStatement.setString(4, values[3].trim());

            preparedStatement.execute();

        }
    } catch (SQLException e) {
        throw new GeoResolverException("Error while executing SQL query", e);
    } catch (IOException e) {
        throw new GeoResolverException("Error while accessing input file", e);
    }

    log.info("Finished populating Database for country data.");
    //should close all the connections for memory leaks.
}

From source file:org.etudes.jforum.dao.generic.GenericGradeDAO.java

/**
 * {@inheritDoc}/*from   w  ww. j ava2 s.  co  m*/
 */
public int addNew(Grade grade) throws Exception {
    PreparedStatement p = this.getStatementForAutoKeys("GradeModel.addNew");

    p.setString(1, grade.getContext());
    p.setInt(2, grade.getType());
    p.setInt(3, grade.getForumId());
    p.setInt(4, grade.getTopicId());
    p.setInt(5, grade.getCategoryId());
    p.setFloat(6, grade.getPoints());
    p.setInt(7, grade.isAddToGradeBook() ? 1 : 0);

    if (grade.isMinimumPostsRequired()) {
        p.setInt(8, grade.getMinimumPosts());
        p.setInt(9, 1);
    } else {
        p.setInt(9, 0);
        p.setInt(8, 0);
    }

    this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("GradeModel.lastGeneratedGradeId"));

    int gradeId = this.executeAutoKeysQuery(p);

    p.close();

    return gradeId;
}

From source file:org.wso2.connectedlap.plugin.impl.dao.impl.DeviceTypeDAOImpl.java

public boolean addDeviceMetaData(ConnectedLapDevice connectedLapDevice) throws DeviceMgtPluginException {
    boolean status = false;
    Connection conn;//from w w w .ja v a  2  s.c  o  m
    PreparedStatement stmt = null;
    try {
        conn = DeviceTypeDAO.getConnection();
        String insertQuery = "UPDATE CONNECTEDLAP_DEVICE SET DEVICE_DISC=?, DEVICE_MEMORY=?, DEVICE_CPU_INFO=?, DEVICE_NETWORK=?, DEVICE_CPU_CORE=? WHERE CONNECTEDLAP_DEVICE_ID=?"; //TODO:add query in here  - need to identify which device to be updated.
        stmt = conn.prepareStatement(insertQuery);
        stmt.setFloat(1, connectedLapDevice.getDiscSpace());
        stmt.setFloat(2, connectedLapDevice.getMemory());
        stmt.setString(3, connectedLapDevice.getCpuInfo());
        stmt.setString(4, connectedLapDevice.getNetworkType());
        stmt.setInt(5, connectedLapDevice.getCpuCores());
        stmt.setString(6, connectedLapDevice.getId());
        int rows = stmt.executeUpdate();
        if (rows > 0) {
            status = true;
            if (log.isDebugEnabled()) {
                log.debug("connectedlap device " + "" + " data has been"
                        + " added to the connectedlap database.");
            }
        }
    } catch (SQLException e) {
        String msg = "Error occurred while adding the connectedlap device '" + "" + "' to the connectedlap db.";
        log.error(msg, e);
        throw new DeviceMgtPluginException(msg, e);
    } finally {
        DeviceTypeUtils.cleanupResources(stmt, null);
    }
    return status;
}

From source file:org.jboss.dashboard.dataset.sql.SQLStatement.java

/**
 * Get a JDBC prepared statement representing the SQL sentence.
 *//*from ww w . j av a  2 s  .  c o m*/
public PreparedStatement getPreparedStatement(Connection connection) throws SQLException {
    PreparedStatement preparedStatement = connection.prepareStatement(SQLSentence);
    int psParamIndex = 1;
    Iterator paramIt = SQLParameters.iterator();
    while (paramIt.hasNext()) {
        Object param = paramIt.next();
        if (param instanceof String)
            preparedStatement.setString(psParamIndex, (String) param);
        else if (param instanceof Date)
            preparedStatement.setTimestamp(psParamIndex, new Timestamp(((Date) param).getTime()));
        else if (param instanceof Float)
            preparedStatement.setFloat(psParamIndex, ((Float) param).floatValue());
        else if (param instanceof Double)
            preparedStatement.setDouble(psParamIndex, ((Double) param).doubleValue());
        else if (param instanceof Number)
            preparedStatement.setLong(psParamIndex, ((Number) param).longValue());
        else if (param instanceof Boolean)
            preparedStatement.setBoolean(psParamIndex, ((Boolean) param).booleanValue());
        else if (param instanceof LabelInterval)
            preparedStatement.setString(psParamIndex, ((LabelInterval) param).getLabel());
        psParamIndex++;
    }
    return preparedStatement;
}

From source file:com.talkdesk.geo.GeoCodeRepositoryBuilder.java

/**
 * Format of the file loading data from/* www.  j  a  v  a 2 s  . c  o m*/
 * geonameid         : integer id of record in geonames database
 * name              : name of geographical point (utf8) varchar(200)
 * asciiname         : name of geographical point in plain ascii characters, varchar(200)
 * alternatenames    : alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000)
 * latitude          : latitude in decimal degrees (wgs84)
 * longitude         : longitude in decimal degrees (wgs84)
 * feature class     : see http://www.geonames.org/export/codes.html, char(1)
 * feature code      : see http://www.geonames.org/export/codes.html, varchar(10)
 * country code      : ISO-3166 2-letter country code, 2 characters
 * cc2               : alternate country codes, comma separated, ISO-3166 2-letter country code, 60 characters
 * admin1 code       : fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
 * admin2 code       : code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
 * admin3 code       : code for third level administrative division, varchar(20)
 * admin4 code       : code for fourth level administrative division, varchar(20)
 * population        : bigint (8 byte int)
 * elevation         : in meters, integer
 * dem               : digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat.
 * timezone          : the timezone id (see file timeZone.txt) varchar(40)
 * modification date : date of last modification in yyyy-MM-dd format
 *
 * @throws IOException
 */
public void populateGeoData() throws GeoResolverException {

    try {
        if (connection == null)
            connection = connectToDatabase();
        if (!new File(geocodeDataLocation).exists()) {
            log.error("No Data file found for geoData. please add to data/geodata.tsv ");
            return;
        }

        Path file = FileSystems.getDefault().getPath(geocodeDataLocation);
        Charset charset = Charset.forName("UTF-8");
        BufferedReader inputStream = Files.newBufferedReader(file, charset);
        String buffer;
        PreparedStatement preparedStatement;
        preparedStatement = connection
                .prepareStatement("INSERT INTO geocodes (ID , CITY_NAME, LATITUDE, LONGITUDE, COUNTRY_CODE)"
                        + " VALUES (?,?,?,?,?)");
        while ((buffer = inputStream.readLine()) != null) {
            String[] values = buffer.split("\t");

            preparedStatement.setInt(1, Integer.parseInt(values[0].trim()));
            preparedStatement.setString(2, values[1].trim());
            preparedStatement.setFloat(3, Float.parseFloat(values[4].trim()));
            preparedStatement.setFloat(4, Float.parseFloat(values[5].trim()));
            preparedStatement.setString(5, values[8].trim());

            preparedStatement.execute();

        }
    } catch (SQLException e) {
        throw new GeoResolverException("Error while executing SQL query", e);
    } catch (IOException e) {
        throw new GeoResolverException("Error while accessing input file", e);
    }
    log.info("Finished populating Database.");
    //should close all the connections for memory leaks.
}

From source file:nl.tudelft.stocktrader.mysql.MySQLMarketSummaryDAO.java

public void updateStockPriceVolume(double quantity, Quote quote) throws DAOException {
    BigDecimal priceChangeFactor = StockTraderUtility.getRandomPriceChangeFactor(quote.getPrice());
    BigDecimal newPrice = quote.getPrice().multiply(priceChangeFactor);

    if (newPrice.compareTo(quote.getLow()) == -1) {
        quote.setLow(newPrice);/*from w w  w.  j  ava  2 s .  c  o m*/
    }
    if (newPrice.compareTo(quote.getHigh()) == 1) {
        quote.setHigh(newPrice);
    }

    PreparedStatement updateStockPriceVolumeStat = null;
    try {
        updateStockPriceVolumeStat = sqlConnection.prepareStatement(SQL_UPDATE_STOCKPRICEVOLUME);
        updateStockPriceVolumeStat.setBigDecimal(1, newPrice);
        updateStockPriceVolumeStat.setBigDecimal(2, quote.getLow());
        updateStockPriceVolumeStat.setBigDecimal(3, quote.getHigh());
        updateStockPriceVolumeStat.setBigDecimal(4, newPrice);
        updateStockPriceVolumeStat.setFloat(5, (float) quantity);
        updateStockPriceVolumeStat.setString(6, quote.getSymbol());
        updateStockPriceVolumeStat.executeUpdate();

    } catch (SQLException e) {
        throw new DAOException("", e);
    } finally {
        try {
            if (updateStockPriceVolumeStat != null) {
                updateStockPriceVolumeStat.close();
            }
        } catch (SQLException e) {
            logger.debug("", e);
        }
    }
}

From source file:car_counter.storage.sqlite.SqliteStorage.java

@Override
public void store(Path destinationFile, Collection<DetectedVehicle> detectedVehicles) {
    try {//from   www . j a v  a 2 s  . c  o m
        PreparedStatement statement = connection.prepareStatement("insert into detected_vehicles "
                + "(timestamp, initial_location, end_location, speed, colour, video_file) values "
                + "(?, ?, ?, ?, ?, ?)");

        for (DetectedVehicle detectedVehicle : detectedVehicles) {
            statement.setLong(1, detectedVehicle.getDateTime().getMillis());
            statement.setLong(2, detectedVehicle.getInitialLocation().ordinal());
            statement.setLong(3, detectedVehicle.getEndLocation().ordinal());

            if (detectedVehicle.getSpeed() == null) {
                statement.setNull(4, Types.NULL);
            } else {
                statement.setFloat(4, detectedVehicle.getSpeed());
            }

            statement.setString(5, null);
            statement.setString(6, destinationFile.getFileName().toString());

            statement.executeUpdate();
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Error inserting records", e);
    }
}

From source file:org.carlspring.tools.csv.dao.CSVDao.java

private void setField(PreparedStatement ps, int i, Field field, String value) throws SQLException {
    // Handle primitives
    if (field.getType().equals("int")) {
        ps.setInt(i, StringUtils.isBlank(value) ? 0 : Integer.parseInt(value));
    } else if (field.getType().equals("long")) {
        ps.setLong(i, StringUtils.isBlank(value) ? 0l : Long.parseLong(value));
    } else if (field.getType().equals("float")) {
        ps.setFloat(i, StringUtils.isBlank(value) ? 0f : Float.parseFloat(value));
    } else if (field.getType().equals("double")) {
        ps.setDouble(i, StringUtils.isBlank(value) ? 0d : Double.parseDouble(value));
    } else if (field.getType().equals("boolean")) {
        ps.setBoolean(i, StringUtils.isBlank(value) && Boolean.parseBoolean(value));
    }// w w w  .  j a v  a 2s  .c om
    // Handle objects
    else if (field.getType().equals("java.lang.String")) {
        ps.setString(i, StringUtils.isBlank(value) ? null : value);
    } else if (field.getType().equals("java.sql.Date")) {
        ps.setDate(i, StringUtils.isBlank(value) ? null : Date.valueOf(value));
    } else if (field.getType().equals("java.sql.Timestamp")) {
        ps.setTimestamp(i, StringUtils.isBlank(value) ? null : Timestamp.valueOf(value));
    } else if (field.getType().equals("java.math.BigDecimal")) {
        ps.setBigDecimal(i, StringUtils.isBlank(value) ? null : new BigDecimal(Long.parseLong(value)));
    }
}

From source file:org.plista.kornakapi.core.storage.MySqlStorage.java

@Override
public void batchSetPreferences(Iterator<Preference> preferences, int batchSize) throws IOException {
    Connection conn = null;/*from w w w .j  a  v  a  2s  .  c o m*/
    PreparedStatement stmt = null;

    try {
        conn = dataSource.getConnection();
        stmt = conn.prepareStatement(IMPORT_QUERY);

        int recordsQueued = 0;

        while (preferences.hasNext()) {
            Preference preference = preferences.next();
            stmt.setLong(1, preference.getUserID());
            stmt.setLong(2, preference.getItemID());
            stmt.setFloat(3, preference.getValue());
            stmt.addBatch();

            if (++recordsQueued % batchSize == 0) {
                stmt.executeBatch();
                log.info("imported {} records in batch", recordsQueued);
            }
        }

        if (recordsQueued % batchSize != 0) {
            stmt.executeBatch();
            log.info("imported {} records in batch. done.", recordsQueued);
        }

    } catch (SQLException e) {
        throw new IOException(e);
    } finally {
        IOUtils.quietClose(stmt);
        IOUtils.quietClose(conn);
    }
}

From source file:com.me.Controller.AddBookController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView mav = new ModelAndView();
    String action = request.getParameter("action");
    if (action.equals("get")) {
        String number = request.getParameter("noOfBooks");
        int noOfBooks = Integer.parseInt(number);
        if (noOfBooks > 0) {
            mav.addObject("numberBooks", noOfBooks);
            mav.setViewName("Books");
        }/*from   w  w w  . ja va2  s . co  m*/
    } else if (action.equals("post")) {
        DAO dao = new DAO();
        Connection conn = null;
        PreparedStatement preparedStatement = null;
        try {

            conn = dao.getConnection();
            String[] isbn = request.getParameterValues("isbn");
            String[] title = request.getParameterValues("title");
            String[] authors = request.getParameterValues("authors");
            String[] price = request.getParameterValues("Price");
            String insertQuery = "insert into books(isbn,title,authors,price)" + "values(?,?,?,?)";
            int count = 0;
            for (int i = 0; i < isbn.length; i++) {

                preparedStatement = conn.prepareStatement(insertQuery);
                preparedStatement.setString(1, isbn[i]);
                preparedStatement.setString(2, title[i]);
                preparedStatement.setString(3, authors[i]);
                preparedStatement.setFloat(4, Float.parseFloat(price[i]));
                int result = preparedStatement.executeUpdate();
                count++;
            }
            mav.addObject("noOfRecords", count);
            mav.setViewName("Result");
        } finally {
            dao.closeConnection(conn);
            dao.closeStatement(preparedStatement);
        }

    }

    return mav;
}