Example usage for java.sql PreparedStatement setBigDecimal

List of usage examples for java.sql PreparedStatement setBigDecimal

Introduction

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

Prototype

void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.math.BigDecimal value.

Usage

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  .ja  v  a  2  s  .  co  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: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);/*from   w  ww.  j  a  v  a2 s.co  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) {

    } 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:org.adempiere.pipo2.IDFinder.java

/**
 * Get ID from column value for a table.
 *
 * @param tableName//from w w w .j  a va  2  s. com
 * @param columName
 * @param value
 * @param AD_Client_ID
 * @param trxName
 */
public static int findIdByColumn(String tableName, String columnName, Object value, int AD_Client_ID,
        boolean ignorecase, String trxName) {
    int id = 0;

    if (value == null)
        return id;

    //construct cache key
    StringBuilder key = new StringBuilder();
    key.append(tableName).append(".").append(columnName).append("=").append(value.toString())
            .append(" AND AD_Client_ID=").append(AD_Client_ID);

    //check cache
    if (idCache.containsKey(key.toString()))
        return idCache.get(key.toString());

    StringBuffer sqlB = new StringBuffer("SELECT ").append(tableName).append("_ID FROM ").append(tableName)
            .append(" WHERE ").append(" AD_Client_ID IN (0, ?) AND ");

    Object[] params = null;
    String[] columns = null;
    if (columnName.indexOf(",") > 0 && value instanceof String) {
        columns = columnName.split("[,]");
        String[] values = ((String) value).split("[,]");
        List<Object> paramList = new ArrayList<Object>();
        for (int i = 0; i < columns.length; i++) {
            if (i > 0)
                sqlB.append(" AND ");
            if (ignorecase) {
                sqlB.append("UPPER(").append(columns[i]).append(")=? ");
            } else {
                sqlB.append(columns[i]).append("=? ");
            }
            try {
                byte[] bytes = Hex.decodeHex(values[i].toCharArray());
                String s = new String(bytes, "UTF-8");
                if (ignorecase) {
                    paramList.add(s.toUpperCase());
                } else {
                    paramList.add(s);
                }
            } catch (DecoderException e) {
                throw new RuntimeException(e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        params = paramList.toArray();
    } else {
        if (ignorecase && value != null && value instanceof String) {
            sqlB.append("UPPER(").append(columnName).append(") =? ");
            params = new Object[] { ((String) value).toUpperCase() };
        } else {
            sqlB.append(columnName).append(" =? ");
            params = new Object[] { value };
        }
        columns = new String[] { columnName };
    }

    sqlB.append(" Order By AD_Client_ID Desc, ").append(tableName).append("_ID");

    MTable table = MTable.get(Env.getCtx(), tableName);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sqlB.toString(), trxName);
        pstmt.setInt(1, AD_Client_ID);
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];
            if (param instanceof String) {
                String s = (String) param;
                MColumn column = table.getColumn(columns[i]);
                if (column.getAD_Reference_ID() == DisplayType.Amount
                        || column.getAD_Reference_ID() == DisplayType.Number
                        || column.getAD_Reference_ID() == DisplayType.CostPrice
                        || column.getAD_Reference_ID() == DisplayType.Quantity)
                    pstmt.setBigDecimal(i + 2, new BigDecimal(s));
                else if (column.getAD_Reference_ID() == DisplayType.Date
                        || column.getAD_Reference_ID() == DisplayType.DateTime)
                    pstmt.setTimestamp(i + 2, Timestamp.valueOf(s));
                else if (column.getAD_Reference_ID() == DisplayType.Integer)
                    pstmt.setInt(i + 2, Integer.parseInt(s));
                else
                    pstmt.setString(i + 2, s);
            } else if (param instanceof Integer) {
                pstmt.setInt(i + 2, ((Integer) param).intValue());
            } else {
                pstmt.setObject(i + 2, param);
            }
        }

        rs = pstmt.executeQuery();
        if (rs.next())
            id = rs.getInt(1);
    } catch (Exception e) {
        throw new DatabaseAccessException(e);
    } finally {
        DB.close(rs, pstmt);
    }

    //update cache
    if (id > 0)
        idCache.put(key.toString(), id);

    return id;
}

From source file:org.apache.cocoon.util.JDBCTypeConversions.java

/**
 * Set the Statement column so that the results are mapped correctly.
 *
 * @param statement the prepared statement
 * @param position the position of the column
 * @param value the value of the column//w ww  . j a v  a  2  s. c o  m
 */
public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject)
        throws Exception {
    if (value instanceof String) {
        value = ((String) value).trim();
    }
    if (typeObject == null) {
        throw new SQLException("Can't set column because the type is unrecognized");
    }
    if (value == null) {
        /** If the value is null, set the column value null and return **/
        statement.setNull(position, typeObject.intValue());
        return;
    }
    if ("".equals(value)) {
        switch (typeObject.intValue()) {
        case Types.CHAR:
        case Types.CLOB:
        case Types.VARCHAR:
            /** If the value is an empty string and the column is
            a string type, we can continue **/
            break;
        default:
            /** If the value is an empty string and the column
            is something else, we treat it as a null value **/
            statement.setNull(position, typeObject.intValue());
            return;
        }
    }

    File file = null;
    int length = -1;
    InputStream asciiStream = null;

    //System.out.println("========================================================================");
    //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue());
    switch (typeObject.intValue()) {
    case Types.CLOB:
        //System.out.println("CLOB");
        Clob clob = null;
        if (value instanceof Clob) {
            clob = (Clob) value;
        } else if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
            clob = new ClobHelper(asciiStream, length);
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new ByteArrayInputStream(asciiText.getBytes());
            length = asciiText.length();
            clob = new ClobHelper(asciiStream, length);
        }

        statement.setClob(position, clob);
        break;
    case Types.CHAR:
        // simple large object, e.g. Informix's TEXT
        //System.out.println("CHAR");

        if (value instanceof File) {
            File asciiFile = (File) value;
            asciiStream = new BufferedInputStream(new FileInputStream(asciiFile));
            length = (int) asciiFile.length();
        } else if (value instanceof JDBCxlobHelper) {
            asciiStream = ((JDBCxlobHelper) value).inputStream;
            length = ((JDBCxlobHelper) value).length;
        } else if (value instanceof Source) {
            asciiStream = ((Source) value).getInputStream();
            length = (int) ((Source) value).getContentLength();
        } else if (value instanceof Part) {
            Part anyFile = (Part) value;
            asciiStream = new BufferedInputStream(anyFile.getInputStream());
            length = anyFile.getSize();
            clob = new ClobHelper(asciiStream, length);
        } else {
            String asciiText = value.toString();
            asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes()));
            length = asciiText.length();
        }

        statement.setAsciiStream(position, asciiStream, length);
        break;
    case Types.BIGINT:
        //System.out.println("BIGINT");
        BigDecimal bd = null;

        if (value instanceof BigDecimal) {
            bd = (BigDecimal) value;
        } else if (value instanceof Number) {
            bd = BigDecimal.valueOf(((Number) value).longValue());
        } else {
            bd = new BigDecimal(value.toString());
        }

        statement.setBigDecimal(position, bd);
        break;
    case Types.TINYINT:
        //System.out.println("TINYINT");
        Byte b = null;

        if (value instanceof Byte) {
            b = (Byte) value;
        } else if (value instanceof Number) {
            b = new Byte(((Number) value).byteValue());
        } else {
            b = new Byte(value.toString());
        }

        statement.setByte(position, b.byteValue());
        break;
    case Types.DATE:
        //System.out.println("DATE");
        Date d = null;

        if (value instanceof Date) {
            d = (Date) value;
        } else if (value instanceof java.util.Date) {
            d = new Date(((java.util.Date) value).getTime());
        } else if (value instanceof Calendar) {
            d = new Date(((Calendar) value).getTime().getTime());
        } else {
            d = Date.valueOf(value.toString());
        }

        statement.setDate(position, d);
        break;
    case Types.DOUBLE:
        //System.out.println("DOUBLE");
        double db;

        if (value instanceof Number) {
            db = (((Number) value).doubleValue());
        } else {
            db = Double.parseDouble(value.toString());
        }
        statement.setDouble(position, db);
        break;
    case Types.FLOAT:
        //System.out.println("FLOAT");
        float f;

        if (value instanceof Number) {
            f = (((Number) value).floatValue());
        } else {
            f = Float.parseFloat(value.toString());
        }
        statement.setFloat(position, f);
        break;
    case Types.NUMERIC:
        //System.out.println("NUMERIC");
        long l;

        if (value instanceof Number) {
            l = (((Number) value).longValue());
        } else {
            l = Long.parseLong(value.toString());
        }

        statement.setLong(position, l);
        break;
    case Types.SMALLINT:
        //System.out.println("SMALLINT");
        Short s = null;

        if (value instanceof Short) {
            s = (Short) value;
        } else if (value instanceof Number) {
            s = new Short(((Number) value).shortValue());
        } else {
            s = new Short(value.toString());
        }

        statement.setShort(position, s.shortValue());
        break;
    case Types.TIME:
        //System.out.println("TIME");
        Time t = null;

        if (value instanceof Time) {
            t = (Time) value;
        } else if (value instanceof java.util.Date) {
            t = new Time(((java.util.Date) value).getTime());
        } else {
            t = Time.valueOf(value.toString());
        }

        statement.setTime(position, t);
        break;
    case Types.TIMESTAMP:
        //System.out.println("TIMESTAMP");
        Timestamp ts = null;

        if (value instanceof Time) {
            ts = (Timestamp) value;
        } else if (value instanceof java.util.Date) {
            ts = new Timestamp(((java.util.Date) value).getTime());
        } else {
            ts = Timestamp.valueOf(value.toString());
        }

        statement.setTimestamp(position, ts);
        break;
    case Types.ARRAY:
        //System.out.println("ARRAY");
        statement.setArray(position, (Array) value); // no way to convert string to array
        break;
    case Types.STRUCT:
        //System.out.println("STRUCT");
    case Types.OTHER:
        //System.out.println("OTHER");
        statement.setObject(position, value);
        break;
    case Types.LONGVARBINARY:
        //System.out.println("LONGVARBINARY");
        statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime()));
        break;
    case Types.VARCHAR:
        //System.out.println("VARCHAR");
        statement.setString(position, value.toString());
        break;
    case Types.BLOB:
        //System.out.println("BLOB");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else {
            Blob blob = null;
            if (value instanceof Blob) {
                blob = (Blob) value;
            } else if (value instanceof File) {
                file = (File) value;
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof String) {
                file = new File((String) value);
                blob = new BlobHelper(new FileInputStream(file), (int) file.length());
            } else if (value instanceof Part) {
                Part anyFile = (Part) value;
                blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize());
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            statement.setBlob(position, blob);
        }
        break;
    case Types.VARBINARY:
        //System.out.println("VARBINARY");
        if (value instanceof JDBCxlobHelper) {
            statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream,
                    ((JDBCxlobHelper) value).length);
        } else if (value instanceof Source) {
            statement.setBinaryStream(position, ((Source) value).getInputStream(),
                    (int) ((Source) value).getContentLength());
        } else if (value instanceof Part) {
            statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize());
        } else {
            if (value instanceof File) {
                file = (File) value;
            } else if (value instanceof String) {
                file = new File((String) value);
            } else {
                throw new SQLException("Invalid type for blob: " + value.getClass().getName());
            }
            //InputStream input = new BufferedInputStream(new FileInputStream(file));
            FileInputStream input = new FileInputStream(file);
            statement.setBinaryStream(position, input, (int) file.length());
        }
        break;
    case Types.INTEGER:
        //System.out.println("INTEGER");
        Integer i = null;
        if (value instanceof Integer) {
            i = (Integer) value;
        } else if (value instanceof Number) {
            i = new Integer(((Number) value).intValue());
        } else {
            i = new Integer(value.toString());
        }
        statement.setInt(position, i.intValue());
        break;
    case Types.BIT:
        //System.out.println("BIT");
        Boolean bo = null;
        if (value instanceof Boolean) {
            bo = (Boolean) value;
        } else if (value instanceof Number) {
            bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1);
        } else {
            bo = BooleanUtils.toBooleanObject(value.toString());
        }
        statement.setBoolean(position, bo.booleanValue());
        break;

    default:
        //System.out.println("default");
        throw new SQLException("Impossible exception - invalid type ");
    }
    //System.out.println("========================================================================");
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * {@inheritDoc}/* ww w.  j  a v a2  s  . c  o m*/
 */
public Iterator query(Database model, String sql, Collection parameters, Table[] queryHints)
        throws DatabaseOperationException {
    Connection connection = borrowConnection();
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    Iterator answer = null;

    try {
        statement = connection.prepareStatement(sql);

        int paramIdx = 1;

        for (Iterator iter = parameters.iterator(); iter.hasNext(); paramIdx++) {
            Object arg = iter.next();

            if (arg instanceof BigDecimal) {
                // to avoid scale problems because setObject assumes a scale of 0
                statement.setBigDecimal(paramIdx, (BigDecimal) arg);
            } else {
                statement.setObject(paramIdx, arg);
            }
        }
        resultSet = statement.executeQuery();
        answer = createResultSetIterator(model, resultSet, queryHints);
        return answer;
    } catch (SQLException ex) {
        throw new DatabaseOperationException("Error while performing a query", ex);
    } finally {
        // if any exceptions are thrown, close things down
        // otherwise we're leaving it open for the iterator
        if (answer == null) {
            closeStatement(statement);
            returnConnection(connection);
        }
    }
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * {@inheritDoc}//  w w  w  .j  av  a  2s . co m
 */
public List fetch(Database model, String sql, Collection parameters, Table[] queryHints, int start, int end)
        throws DatabaseOperationException {
    Connection connection = borrowConnection();
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    List result = new ArrayList();

    try {
        statement = connection.prepareStatement(sql);

        int paramIdx = 1;

        for (Iterator iter = parameters.iterator(); iter.hasNext(); paramIdx++) {
            Object arg = iter.next();

            if (arg instanceof BigDecimal) {
                // to avoid scale problems because setObject assumes a scale of 0
                statement.setBigDecimal(paramIdx, (BigDecimal) arg);
            } else {
                statement.setObject(paramIdx, arg);
            }
        }
        resultSet = statement.executeQuery();

        int rowIdx = 0;

        for (ModelBasedResultSetIterator it = createResultSetIterator(model, resultSet, queryHints); ((end < 0)
                || (rowIdx <= end)) && it.hasNext(); rowIdx++) {
            if (rowIdx >= start) {
                result.add(it.next());
            } else {
                it.advance();
            }
        }
    } catch (SQLException ex) {
        // any other exception comes from the iterator which closes the resources automatically
        closeStatement(statement);
        returnConnection(connection);
        throw new DatabaseOperationException("Error while fetching data from the database", ex);
    }
    return result;
}

From source file:org.apache.ddlutils.platform.PlatformImplBase.java

/**
 * This is the core method to set the parameter of a prepared statement to a given value.
 * The primary purpose of this method is to call the appropriate method on the statement,
 * and to give database-specific implementations the ability to change this behavior.
 * //from  www. j av  a2s .c o m
 * @param statement The statement
 * @param sqlIndex  The parameter index
 * @param typeCode  The JDBC type code
 * @param value     The value
 * @throws SQLException If an error occurred while setting the parameter value
 */
protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value)
        throws SQLException {
    if (value == null) {
        statement.setNull(sqlIndex, typeCode);
    } else if (value instanceof String) {
        statement.setString(sqlIndex, (String) value);
    } else if (value instanceof byte[]) {
        statement.setBytes(sqlIndex, (byte[]) value);
    } else if (value instanceof Boolean) {
        statement.setBoolean(sqlIndex, ((Boolean) value).booleanValue());
    } else if (value instanceof Byte) {
        statement.setByte(sqlIndex, ((Byte) value).byteValue());
    } else if (value instanceof Short) {
        statement.setShort(sqlIndex, ((Short) value).shortValue());
    } else if (value instanceof Integer) {
        statement.setInt(sqlIndex, ((Integer) value).intValue());
    } else if (value instanceof Long) {
        statement.setLong(sqlIndex, ((Long) value).longValue());
    } else if (value instanceof BigDecimal) {
        // setObject assumes a scale of 0, so we rather use the typed setter
        statement.setBigDecimal(sqlIndex, (BigDecimal) value);
    } else if (value instanceof Float) {
        statement.setFloat(sqlIndex, ((Float) value).floatValue());
    } else if (value instanceof Double) {
        statement.setDouble(sqlIndex, ((Double) value).doubleValue());
    } else {
        statement.setObject(sqlIndex, value, typeCode);
    }
}

From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java

private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index)
        throws SQLException {
    switch (targetSqlType) {
    case Types.INTEGER:
        pstmt.setInt(index, Integer.parseInt(argument));
        break;//  w w  w  .j ava 2s .c o  m
    case Types.DECIMAL:
    case Types.NUMERIC:
        pstmt.setBigDecimal(index, new BigDecimal(argument));
        break;
    case Types.DOUBLE:
    case Types.FLOAT:
        pstmt.setDouble(index, Double.parseDouble(argument));
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        pstmt.setString(index, argument);
        break;
    case Types.BIT:
    case Types.BOOLEAN:
        pstmt.setBoolean(index, Boolean.parseBoolean(argument));
        break;
    case Types.BIGINT:
        pstmt.setLong(index, Long.parseLong(argument));
        break;
    case Types.DATE:
        pstmt.setDate(index, Date.valueOf(argument));
        break;
    case Types.REAL:
        pstmt.setFloat(index, Float.parseFloat(argument));
        break;
    case Types.TINYINT:
        pstmt.setByte(index, Byte.parseByte(argument));
        break;
    case Types.SMALLINT:
        pstmt.setShort(index, Short.parseShort(argument));
        break;
    case Types.TIMESTAMP:
        pstmt.setTimestamp(index, Timestamp.valueOf(argument));
        break;
    case Types.TIME:
        pstmt.setTime(index, Time.valueOf(argument));
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        pstmt.setBytes(index, argument.getBytes());
        break;
    case Types.NULL:
        pstmt.setNull(index, targetSqlType);
        break;
    default:
        pstmt.setObject(index, argument, targetSqlType);
    }
}

From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java

/**
 * Set the given value as a parameter to the statement.
 *//*from ww  w  .  j  a va2s  .co  m*/
public void setBigDecimal(PreparedStatement stmnt, int idx, BigDecimal val, Column col) throws SQLException {
    if ((col != null && col.isCompatible(Types.VARCHAR, null, 0, 0))
            || (col == null && storeLargeNumbersAsStrings))
        setString(stmnt, idx, val.toString(), col);
    else
        stmnt.setBigDecimal(idx, val);
}

From source file:org.apache.phoenix.end2end.DateTimeIT.java

private static void initDateTableValues(String tablename, Connection conn, String tenantId, Date startDate)
        throws Exception {
    double dateIncrement = 2.0;
    PreparedStatement stmt = conn.prepareStatement("upsert into " + tablename + "(" + "    ORGANIZATION_ID, "
            + "    \"DATE\", " + "    FEATURE, " + "    UNIQUE_USERS, " + "    TRANSACTIONS, "
            + "    CPU_UTILIZATION, " + "    DB_UTILIZATION, " + "    REGION, " + "    IO_TIME)"
            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    stmt.setString(1, tenantId);//from w  ww .j  a va  2s  .  c  om
    stmt.setDate(2, startDate);
    stmt.setString(3, "A");
    stmt.setInt(4, 10);
    stmt.setLong(5, 100L);
    stmt.setBigDecimal(6, BigDecimal.valueOf(0.5));
    stmt.setBigDecimal(7, BigDecimal.valueOf(0.2));
    stmt.setString(8, R2);
    stmt.setNull(9, Types.BIGINT);
    stmt.execute();

    startDate = new Date(startDate.getTime() + (long) (QueryConstants.MILLIS_IN_DAY * dateIncrement));
    stmt.setString(1, tenantId);
    stmt.setDate(2, startDate);
    stmt.setString(3, "B");
    stmt.setInt(4, 20);
    stmt.setLong(5, 200);
    stmt.setBigDecimal(6, BigDecimal.valueOf(1.0));
    stmt.setBigDecimal(7, BigDecimal.valueOf(0.4));
    stmt.setString(8, null);
    stmt.setLong(9, 2000);
    stmt.execute();

    startDate = new Date(startDate.getTime() + (long) (QueryConstants.MILLIS_IN_DAY * dateIncrement));
    stmt.setString(1, tenantId);
    stmt.setDate(2, startDate);
    stmt.setString(3, "C");
    stmt.setInt(4, 30);
    stmt.setLong(5, 300);
    stmt.setBigDecimal(6, BigDecimal.valueOf(2.5));
    stmt.setBigDecimal(7, BigDecimal.valueOf(0.6));
    stmt.setString(8, R1);
    stmt.setNull(9, Types.BIGINT);
    stmt.execute();

    startDate = new Date(startDate.getTime() + (long) (QueryConstants.MILLIS_IN_DAY * dateIncrement));
    stmt.setString(1, tenantId);
    stmt.setDate(2, startDate);
    stmt.setString(3, "D");
    stmt.setInt(4, 40);
    stmt.setLong(5, 400);
    stmt.setBigDecimal(6, BigDecimal.valueOf(3.0));
    stmt.setBigDecimal(7, BigDecimal.valueOf(0.8));
    stmt.setString(8, R1);
    stmt.setLong(9, 4000);
    stmt.execute();

    startDate = new Date(startDate.getTime() + (long) (QueryConstants.MILLIS_IN_DAY * dateIncrement));
    stmt.setString(1, tenantId);
    stmt.setDate(2, startDate);
    stmt.setString(3, "E");
    stmt.setInt(4, 50);
    stmt.setLong(5, 500);
    stmt.setBigDecimal(6, BigDecimal.valueOf(3.5));
    stmt.setBigDecimal(7, BigDecimal.valueOf(1.2));
    stmt.setString(8, R2);
    stmt.setLong(9, 5000);
    stmt.execute();

    startDate = new Date(startDate.getTime() + (long) (QueryConstants.MILLIS_IN_DAY * dateIncrement));
    stmt.setString(1, tenantId);
    stmt.setDate(2, startDate);
    stmt.setString(3, "F");
    stmt.setInt(4, 60);
    stmt.setLong(5, 600);
    stmt.setBigDecimal(6, BigDecimal.valueOf(4.0));
    stmt.setBigDecimal(7, BigDecimal.valueOf(1.4));
    stmt.setString(8, null);
    stmt.setNull(9, Types.BIGINT);
    stmt.execute();
}