List of usage examples for java.sql PreparedStatement setFloat
void setFloat(int parameterIndex, float x) throws SQLException;
float
value. From source file:org.stanwood.media.database.sdb.AbstractGenericDatabase.java
/** * This is used to create a PreparedStatement from the given SQL. The SQL should * contain ? were the params should be inserted. * * @see PreparedStatement/*from w w w .ja v a 2 s.c o m*/ * @param connection a connection to the database * @param sql the statements SQL * @param params the parameters to place into the statement * @return a Prepared Statement * @throws SQLException thrown if their is a problem creating the statement */ @Override public PreparedStatement getStatement(Connection connection, String sql, Object[] params) throws SQLException { PreparedStatement stmt = null; log.debug("Preparing statement"); //$NON-NLS-1$ stmt = getStatement(connection, sql); log.debug("Setting variables"); //$NON-NLS-1$ for (int i = 0; i < params.length; i++) { if (params[i] == null) { throw new RuntimeException("A null param at index " + i //$NON-NLS-1$ + " is unsupported."); //$NON-NLS-1$ } else if (params[i] instanceof String) { stmt.setString(i + 1, (String) params[i]); } else if (params[i] instanceof Float) { stmt.setFloat(i + 1, (Float) params[i]); } else if (params[i] instanceof Integer) { stmt.setInt(i + 1, (Integer) params[i]); } else if (params[i] instanceof Boolean) { stmt.setBoolean(i + 1, (Boolean) params[i]); } else if (params[i] instanceof Long) { stmt.setLong(i + 1, (Long) params[i]); } else { throw new RuntimeException("A param type of " //$NON-NLS-1$ + params[i].getClass().getName() + " is unsupported."); //$NON-NLS-1$ } } return stmt; }
From source file:nl.tudelft.stocktrader.derby.DerbyOrderDAO.java
public Order createOrder(String userID, String symbol, String orderType, double quantity, int holdingID) throws DAOException { int orderID = 0; Calendar minCalender = Calendar.getInstance(); minCalender.setTimeInMillis(0);//from w w w . j av a 2 s .c o m Order order = new Order(orderID, orderType, StockTraderUtility.ORDER_STATUS_OPEN, Calendar.getInstance(), minCalender, quantity, BigDecimal.valueOf(1), StockTraderUtility.getOrderFee(orderType), symbol); order.setHoldingId(holdingID); PreparedStatement getAccountId = null; try { getAccountId = sqlConnection.prepareStatement(SQL_GET_ACCOUNTID); getAccountId.setString(1, userID); ResultSet rs = getAccountId.executeQuery(); if (rs.next()) { order.setAccountId(rs.getInt(1)); } } catch (SQLException e) { throw new DAOException("", e); } finally { if (getAccountId != null) { try { getAccountId.close(); } catch (SQLException e) { logger.debug("", e); } } } PreparedStatement insertOrder = null; PreparedStatement selectOrderID = null; try { insertOrder = sqlConnection.prepareStatement(SQL_INSERT_ORDER); insertOrder.setBigDecimal(1, order.getOrderFee()); insertOrder.setBigDecimal(2, order.getPrice()); insertOrder.setString(3, order.getSymbol()); // FIXED: metro used Double rather than double // insertOrder.setFloat(4, (float) order.getQuantity()); insertOrder.setFloat(4, order.getQuantity().floatValue()); insertOrder.setString(5, order.getOrderType()); insertOrder.setInt(6, order.getAccountId()); insertOrder.setInt(7, order.getHoldingId()); insertOrder.executeUpdate(); selectOrderID = sqlConnection.prepareStatement(SQL_SELECT_ORDER_ID); // ORDERFEE = ? AND PRICE = ? AND QUOTE_SYMBOL = ? AND QUANTITY = ? // ORDERTYPE = ? ORDERSTATUS = ? AND ACCOUNT_ACCOUNTID = ? // HOLDING_HOLDINGID = ?" selectOrderID.setBigDecimal(1, order.getOrderFee()); selectOrderID.setBigDecimal(2, order.getPrice()); selectOrderID.setString(3, order.getSymbol()); selectOrderID.setDouble(4, order.getQuantity()); selectOrderID.setString(5, order.getOrderType()); selectOrderID.setString(6, "open"); selectOrderID.setInt(7, order.getAccountId()); selectOrderID.setInt(8, order.getHoldingId()); ResultSet rs = selectOrderID.executeQuery(); if (rs.next()) { try { order.setOrderID(rs.getInt(1)); } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } } catch (SQLException e) { throw new DAOException("", e); } finally { if (insertOrder != null) { try { insertOrder.close(); } catch (SQLException e) { logger.debug("", e); } } if (selectOrderID != null) { try { selectOrderID.close(); } catch (SQLException e) { logger.debug("", e); } } } return order; }
From source file:nl.tudelft.stocktrader.mysql.MySQLOrderDAO.java
public Order createOrder(String userID, String symbol, String orderType, double quantity, int holdingID) throws DAOException { int orderID = 0; Calendar minCalender = Calendar.getInstance(); minCalender.setTimeInMillis(0);/* www . j a va 2s . com*/ Order order = new Order(orderID, orderType, StockTraderUtility.ORDER_STATUS_OPEN, Calendar.getInstance(), minCalender, quantity, BigDecimal.valueOf(1), StockTraderUtility.getOrderFee(orderType), symbol); order.setHoldingId(holdingID); PreparedStatement getAccountId = null; try { getAccountId = sqlConnection.prepareStatement(SQL_GET_ACCOUNTID); getAccountId.setString(1, userID); ResultSet rs = getAccountId.executeQuery(); if (rs.next()) { order.setAccountId(rs.getInt(1)); } } catch (SQLException e) { } finally { if (getAccountId != null) { try { getAccountId.close(); } catch (SQLException e) { logger.debug("", e); } } } PreparedStatement insertOrder = null; PreparedStatement selectOrderID = null; try { insertOrder = sqlConnection.prepareStatement(SQL_INSERT_ORDER); insertOrder.setBigDecimal(1, order.getOrderFee()); insertOrder.setBigDecimal(2, order.getPrice()); insertOrder.setString(3, order.getSymbol()); // FIXED: metro used Double rather than double // insertOrder.setFloat(4, (float) order.getQuantity()); insertOrder.setFloat(4, order.getQuantity().floatValue()); insertOrder.setString(5, order.getOrderType()); insertOrder.setInt(6, order.getAccountId()); insertOrder.setInt(7, order.getHoldingId()); insertOrder.executeUpdate(); selectOrderID = sqlConnection.prepareStatement(SQL_SELECT_ORDER_ID); // ORDERFEE = ? AND PRICE = ? AND QUOTE_SYMBOL = ? AND QUANTITY = ? // ORDERTYPE = ? ORDERSTATUS = ? AND ACCOUNT_ACCOUNTID = ? // HOLDING_HOLDINGID = ?" selectOrderID.setBigDecimal(1, order.getOrderFee()); selectOrderID.setBigDecimal(2, order.getPrice()); selectOrderID.setString(3, order.getSymbol()); selectOrderID.setDouble(4, order.getQuantity()); selectOrderID.setString(5, order.getOrderType()); selectOrderID.setString(6, "open"); selectOrderID.setInt(7, order.getAccountId()); selectOrderID.setInt(8, order.getHoldingId()); ResultSet rs = selectOrderID.executeQuery(); if (rs.next()) { try { order.setOrderID(rs.getInt(1)); } finally { try { rs.close(); } catch (SQLException e) { logger.debug("", e); } } } } catch (SQLException e) { throw new DAOException("", e); } finally { if (insertOrder != null) { try { insertOrder.close(); } catch (SQLException e) { logger.debug("", e); } } if (selectOrderID != null) { try { selectOrderID.close(); } catch (SQLException e) { logger.debug("", e); } } } return order; }
From source file:net.solarnetwork.node.dao.jdbc.power.JdbcPowerDatumDao.java
@Override protected void setStoreStatementValues(PowerDatum datum, PreparedStatement ps) throws SQLException { int col = 1;// w ww .j a v a2 s . co m ps.setTimestamp(col++, new java.sql.Timestamp( datum.getCreated() == null ? System.currentTimeMillis() : datum.getCreated().getTime())); ps.setString(col++, datum.getSourceId() == null ? "" : datum.getSourceId()); if (datum.getLocationId() == null) { ps.setNull(col++, Types.BIGINT); } else { ps.setLong(col++, datum.getLocationId()); } if (datum.getWatts() == null) { ps.setNull(col++, Types.INTEGER); } else { ps.setInt(col++, datum.getWatts()); } if (datum.getBatteryVolts() == null) { ps.setNull(col++, Types.FLOAT); } else { ps.setFloat(col++, datum.getBatteryVolts()); } if (datum.getBatteryAmpHours() == null) { ps.setNull(col++, Types.DOUBLE); } else { ps.setDouble(col++, datum.getBatteryAmpHours()); } if (datum.getDcOutputVolts() == null) { ps.setNull(col++, Types.FLOAT); } else { ps.setFloat(col++, datum.getDcOutputVolts()); } if (datum.getDcOutputAmps() == null) { ps.setNull(col++, Types.FLOAT); } else { ps.setFloat(col++, datum.getDcOutputAmps()); } if (datum.getAcOutputVolts() == null) { ps.setNull(col++, Types.FLOAT); } else { ps.setFloat(col++, datum.getAcOutputVolts()); } if (datum.getAcOutputAmps() == null) { ps.setNull(col++, Types.FLOAT); } else { ps.setFloat(col++, datum.getAcOutputAmps()); } if (datum.getWattHourReading() == null) { ps.setNull(col++, Types.BIGINT); } else { ps.setLong(col++, datum.getWattHourReading()); } if (datum.getAmpHourReading() == null) { ps.setNull(col++, Types.DOUBLE); } else { ps.setDouble(col++, datum.getAmpHourReading()); } }
From source file:com.ushahidi.swiftriver.core.api.dao.impl.JpaPlaceDao.java
/** * Insert new places in a single batch statement * // w w w. jav a 2 s . c om * @param newPlaceIndex * @param drops */ private void batchInsert(final Map<String, List<int[]>> newPlaceIndex, final List<Drop> drops, Sequence seq) { final List<String> hashes = new ArrayList<String>(); hashes.addAll(newPlaceIndex.keySet()); final long startKey = sequenceDao.getIds(seq, hashes.size()); String sql = "INSERT INTO places (id, hash, place_name, " + "place_name_canonical, longitude, latitude) " + "VALUES (?,?,?,?,?,?)"; jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { String hash = hashes.get(i); // Update drops with the newly generated id for (int[] index : newPlaceIndex.get(hash)) { drops.get(index[0]).getPlaces().get(index[1]).setId(startKey + i); } int[] index = newPlaceIndex.get(hash).get(0); Place place = drops.get(index[0]).getPlaces().get(index[1]); ps.setLong(1, place.getId()); ps.setString(2, place.getHash()); ps.setString(3, place.getPlaceName()); ps.setString(4, place.getPlaceNameCanonical()); ps.setFloat(5, place.getLongitude()); ps.setFloat(6, place.getLatitude()); } public int getBatchSize() { return hashes.size(); } }); // Update the droplet_places table insertDropletPlaces(drops); }
From source file:org.wso2.cep.broker.RDBMSBrokerType.java
@Override public void publish(String topic, Object message, BrokerConfiguration brokerConfiguration) throws BrokerEventProcessingException { try {// ww w . java2 s .c om String[] topicItems = topic.split("\\."); String databaseName = topicItems[0].trim(); String tableName = topicItems[1].trim(); ConcurrentHashMap<String, Connection> connectionMap = jdbcConnections.get(brokerConfiguration); if (connectionMap == null) { connectionMap = new ConcurrentHashMap<String, Connection>(); jdbcConnections.put(brokerConfiguration, connectionMap); } Connection connection = connectionMap.get(databaseName); if (connection == null) { Class.forName(driverClassName); connection = DriverManager.getConnection(urlPrefix + "://" + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_HOSTNAME_REFERENCE) + ":" + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_PORT_REFERENCE) + "/" + databaseName + "?user=" + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_USER_NAME_REFERENCE) + "&password=" + brokerConfiguration.getProperties().get(BROKER_CONF_RDBMS_PROPERTY_PASSWORD_REFERENCE)); connectionMap.put(databaseName, connection); } ConcurrentHashMap<String, TableInfo> tableInfoMap = tables.get(brokerConfiguration); TableInfo tableInfo; if (tableInfoMap == null || tableInfoMap.get(topic) == null) { tableInfo = initializeTableInfo(databaseName, tableName, message, brokerConfiguration, connection); if (tableInfoMap == null) { tableInfoMap = new ConcurrentHashMap<String, TableInfo>(); tables.put(brokerConfiguration, tableInfoMap); } } else { tableInfo = tableInfoMap.get(topic); } PreparedStatement preparedStatement = tableInfo.getPreparedStatement(); Map<String, Object> map = (Map<String, Object>) message; Attribute attribute; for (int i = 0; i < tableInfo.getColumnOrder().size(); i++) { attribute = tableInfo.getColumnOrder().get(i); switch (attribute.getType()) { case INT: preparedStatement.setInt(i + 1, (Integer) map.get(attribute.getName())); break; case LONG: preparedStatement.setLong(i + 1, (Long) map.get(attribute.getName())); break; case FLOAT: preparedStatement.setFloat(i + 1, (Float) map.get(attribute.getName())); break; case DOUBLE: preparedStatement.setDouble(i + 1, (Double) map.get(attribute.getName())); break; case STRING: preparedStatement.setString(i + 1, (String) map.get(attribute.getName())); break; case BOOL: preparedStatement.setBoolean(i + 1, (Boolean) map.get(attribute.getName())); break; } } preparedStatement.executeUpdate(); } catch (SQLException e) { log.error(e); } catch (ClassNotFoundException e) { log.error(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 {//from w w w .j a v a 2 s . c o m throw new RuntimeException( "Unknown type of value " + column.getVal() + " for column " + column.getColumnName()); } ++index; } }
From source file:com.novartis.opensource.yada.adaptor.JDBCAdaptor.java
/** * Sets a {@code ?n} parameter value mapped to the correct {@link java.sql.Types#FLOAT} JDBC setter. * @param pstmt the statement in which to set the parameter values * @param index the current parameter/*from w w w . j a va 2s .c om*/ * @param type the data type of the parameter (retained here for logging) * @param val the value to set * @throws SQLException when a parameter cannot be set, for instance if the data type is wrong or unsupported * @since 5.1.0 */ protected void setNumberParameter(PreparedStatement pstmt, int index, char type, String val) throws SQLException { try { float fval = Float.parseFloat(val); pstmt.setFloat(index, fval); } catch (NumberFormatException | NullPointerException e) { l.warn("Error: " + e.getMessage() + " caused by " + e.getClass()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: null"); pstmt.setNull(index, java.sql.Types.INTEGER); } }
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 w w w .ja v a2s . co m 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.wso2.carbon.event.output.adaptor.mysql.MysqlEventAdaptorType.java
private boolean populateStatement(Map<String, Object> map, PreparedStatement stmt, ArrayList<Attribute> colOrder, boolean terminateOnNullValues) throws SQLException { Attribute attribute;// w w w . ja v a 2s . com 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 if (terminateOnNullValues) { return false; } } return true; }