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:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = conn.createStatement();

    stmt.executeUpdate("create table survey (id DECIMAL, name BINARY );");

    String sql = "INSERT INTO survey (id) VALUES(?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);

    pstmt.setBigDecimal(1, new BigDecimal("1.00000"));

    // insert the data
    pstmt.executeUpdate();/*from   w  ww .ja va  2  s.  c om*/

    ResultSet rs = stmt.executeQuery("SELECT * FROM survey");
    while (rs.next()) {
        System.out.print(rs.getString(1));
    }

    rs.close();
    stmt.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial", "root", "root");

    String sql = "INSERT bigdecimal VALUES(?,?)";
    PreparedStatement prest = con.prepareStatement(sql);
    prest.setString(1, "D");
    BigDecimal b = new BigDecimal("111111111111111111111111111111111");
    prest.setBigDecimal(2, b);
    prest.executeUpdate();// ww w.ja v  a 2 s . com
}

From source file:DemoPreparedStatementSetBigDecimal.java

public static void main(String[] args) throws Exception {
    Connection conn = null;//from www .ja va2 s  .  c  om
    PreparedStatement pstmt = null;
    String query = null;
    try {
        conn = getConnection();
        query = "insert into  BIG_DECIMAL_TABLE(id, big_decimal) values(?, ?)";
        pstmt = conn.prepareStatement(query);
        pstmt.setString(1, "001");
        pstmt.setBigDecimal(2, new java.math.BigDecimal("123456789"));
        // execute query, and return number of rows created
        int rowCount = pstmt.executeUpdate();
        System.out.println("rowCount=" + rowCount);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        pstmt.close();
        conn.close();
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);//from   w w  w. j ava 2 s  .c o  m

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);
    String sql = "INSERT INTO mysql_all_table(" + "col_boolean," + "col_byte," + "col_short," + "col_int,"
            + "col_long," + "col_float," + "col_double," + "col_bigdecimal," + "col_string," + "col_date,"
            + "col_time," + "col_timestamp," + "col_asciistream," + "col_binarystream," + "col_blob) "
            + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);

    pstmt.setBoolean(1, true);
    pstmt.setByte(2, (byte) 123);
    pstmt.setShort(3, (short) 123);
    pstmt.setInt(4, 123);
    pstmt.setLong(5, 123L);
    pstmt.setFloat(6, 1.23F);
    pstmt.setDouble(7, 1.23D);
    pstmt.setBigDecimal(8, new BigDecimal(1.23));
    pstmt.setString(9, "a string");
    pstmt.setDate(10, new java.sql.Date(System.currentTimeMillis()));
    pstmt.setTime(11, new Time(System.currentTimeMillis()));
    pstmt.setTimestamp(12, new Timestamp(System.currentTimeMillis()));

    File file = new File("infilename1");
    FileInputStream is = new FileInputStream(file);
    pstmt.setAsciiStream(13, is, (int) file.length());

    file = new File("infilename2");
    is = new FileInputStream(file);
    pstmt.setBinaryStream(14, is, (int) file.length());

    file = new File("infilename3");
    is = new FileInputStream(file);
    pstmt.setBinaryStream(15, is, (int) file.length());

    pstmt.executeUpdate();
}

From source file:examples.KafkaStreamsDemo.java

public static void main(String[] args) throws InterruptedException, SQLException {
    /**/*from  w w w  . j  a  v a2s .co  m*/
     * The example assumes the following SQL schema
     *
     *    DROP DATABASE IF EXISTS beer_sample_sql;
     *    CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci;
     *    USE beer_sample_sql;
     *
     *    CREATE TABLE breweries (
     *       id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       description TEXT,
     *       country VARCHAR(256),
     *       city VARCHAR(256),
     *       state VARCHAR(256),
     *       phone VARCHAR(40),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     *
     *
     *    CREATE TABLE beers (
     *       id VARCHAR(256) NOT NULL,
     *       brewery_id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       category VARCHAR(256),
     *       style VARCHAR(256),
     *       description TEXT,
     *       abv DECIMAL(10,2),
     *       ibu DECIMAL(10,2),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     */
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.err.println("Failed to load MySQL JDBC driver");
    }
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root",
            "secret");
    final PreparedStatement insertBrewery = connection.prepareStatement(
            "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " name=VALUES(name), description=VALUES(description), country=VALUES(country),"
                    + " country=VALUES(country), city=VALUES(city), state=VALUES(state),"
                    + " phone=VALUES(phone), updated_at=VALUES(updated_at)");
    final PreparedStatement insertBeer = connection.prepareStatement(
            "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description),"
                    + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv),"
                    + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)");

    String schemaRegistryUrl = "http://localhost:8081";

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class);

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    KStreamBuilder builder = new KStreamBuilder();

    KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample");

    KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() {
        @Override
        public JsonNode apply(GenericRecord value) {
            ByteBuffer buf = (ByteBuffer) value.get("content");
            try {
                JsonNode doc = MAPPER.readTree(buf.array());
                return doc;
            } catch (IOException e) {
                return null;
            }
        }
    }).branch(new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name")
                    && value.has("description") && value.has("category") && value.has("style")
                    && value.has("abv") && value.has("ibu") && value.has("updated");
        }
    }, new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description")
                    && value.has("country") && value.has("city") && value.has("state") && value.has("phone")
                    && value.has("updated");
        }
    });
    documents[0].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBeer.setString(1, key);
                insertBeer.setString(2, value.get("brewery_id").asText());
                insertBeer.setString(3, value.get("name").asText());
                insertBeer.setString(4, value.get("description").asText());
                insertBeer.setString(5, value.get("category").asText());
                insertBeer.setString(6, value.get("style").asText());
                insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText()));
                insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText()));
                insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBeer.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });
    documents[1].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBrewery.setString(1, key);
                insertBrewery.setString(2, value.get("name").asText());
                insertBrewery.setString(3, value.get("description").asText());
                insertBrewery.setString(4, value.get("country").asText());
                insertBrewery.setString(5, value.get("city").asText());
                insertBrewery.setString(6, value.get("state").asText());
                insertBrewery.setString(7, value.get("phone").asText());
                insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBrewery.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });

    final KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            streams.close();
        }
    }));
}

From source file:com.sf.ddao.factory.param.ParameterHelper.java

public static void bind(PreparedStatement preparedStatement, int idx, Object param, Class<?> clazz,
        Context context) throws SQLException {
    if (clazz == Integer.class || clazz == Integer.TYPE) {
        preparedStatement.setInt(idx, (Integer) param);
    } else if (clazz == String.class) {
        preparedStatement.setString(idx, (String) param);
    } else if (clazz == Long.class || clazz == Long.TYPE) {
        preparedStatement.setLong(idx, (Long) param);
    } else if (clazz == Boolean.class || clazz == Boolean.TYPE) {
        preparedStatement.setBoolean(idx, (Boolean) param);
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        BigInteger bi = (BigInteger) param;
        preparedStatement.setBigDecimal(idx, new BigDecimal(bi));
    } else if (Timestamp.class.isAssignableFrom(clazz)) {
        preparedStatement.setTimestamp(idx, (Timestamp) param);
    } else if (Date.class.isAssignableFrom(clazz)) {
        if (!java.sql.Date.class.isAssignableFrom(clazz)) {
            param = new java.sql.Date(((Date) param).getTime());
        }//from  w  w  w .j a  v  a  2 s . c  om
        preparedStatement.setDate(idx, (java.sql.Date) param);
    } else if (BoundParameter.class.isAssignableFrom(clazz)) {
        ((BoundParameter) param).bindParam(preparedStatement, idx, context);
    } else {
        throw new SQLException("Unimplemented type mapping for " + clazz);
    }
}

From source file:org.openmrs.module.bahmniexports.example.domain.trade.internal.CustomerCreditUpdatePreparedStatementSetter.java

@Override
public void setValues(CustomerCredit customerCredit, PreparedStatement ps) throws SQLException {
    ps.setBigDecimal(1, customerCredit.getCredit().add(FIXED_AMOUNT));
    ps.setLong(2, customerCredit.getId());
}

From source file:com.wabacus.system.datatype.BigdecimalType.java

public void setPreparedStatementValue(int iindex, String value, PreparedStatement pstmt, AbsDatabaseType dbtype)
        throws SQLException {
    log.debug("setBigDecimal(" + iindex + "," + value + ")");
    pstmt.setBigDecimal(iindex, (BigDecimal) label2value(value));
}

From source file:org.hxzon.util.db.springjdbc.StatementCreatorUtils.java

private static void setValue(PreparedStatement ps, int paramIndex, int sqlType, String typeName, Integer scale,
        Object inValue) throws SQLException {

    if (inValue instanceof SqlTypeValue) {
        ((SqlTypeValue) inValue).setTypeValue(ps, paramIndex, sqlType, typeName);
    } else if (inValue instanceof SqlValue) {
        ((SqlValue) inValue).setValue(ps, paramIndex);
    } else if (sqlType == Types.VARCHAR || sqlType == Types.LONGVARCHAR
            || (sqlType == Types.CLOB && isStringValue(inValue.getClass()))) {
        ps.setString(paramIndex, inValue.toString());
    } else if (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) {
        if (inValue instanceof BigDecimal) {
            ps.setBigDecimal(paramIndex, (BigDecimal) inValue);
        } else if (scale != null) {
            ps.setObject(paramIndex, inValue, sqlType, scale);
        } else {/*from  w  ww  . jav  a 2 s. c  om*/
            ps.setObject(paramIndex, inValue, sqlType);
        }
    } else if (sqlType == Types.DATE) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Date) {
                ps.setDate(paramIndex, (java.sql.Date) inValue);
            } else {
                ps.setDate(paramIndex, new java.sql.Date(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setDate(paramIndex, new java.sql.Date(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.DATE);
        }
    } else if (sqlType == Types.TIME) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Time) {
                ps.setTime(paramIndex, (java.sql.Time) inValue);
            } else {
                ps.setTime(paramIndex, new java.sql.Time(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTime(paramIndex, new java.sql.Time(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.TIME);
        }
    } else if (sqlType == Types.TIMESTAMP) {
        if (inValue instanceof java.util.Date) {
            if (inValue instanceof java.sql.Timestamp) {
                ps.setTimestamp(paramIndex, (java.sql.Timestamp) inValue);
            } else {
                ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
            }
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
        } else {
            ps.setObject(paramIndex, inValue, Types.TIMESTAMP);
        }
    } else if (sqlType == SqlTypeValue.TYPE_UNKNOWN) {
        if (isStringValue(inValue.getClass())) {
            ps.setString(paramIndex, inValue.toString());
        } else if (isDateValue(inValue.getClass())) {
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(((java.util.Date) inValue).getTime()));
        } else if (inValue instanceof Calendar) {
            Calendar cal = (Calendar) inValue;
            ps.setTimestamp(paramIndex, new java.sql.Timestamp(cal.getTime().getTime()), cal);
        } else {
            // Fall back to generic setObject call without SQL type specified.
            ps.setObject(paramIndex, inValue);
        }
    } else {
        // Fall back to generic setObject call with SQL type specified.
        ps.setObject(paramIndex, inValue, sqlType);
    }
}

From source file:net.freechoice.model.orm.Map_Account.java

@Override
public PreparedStatementCreator createInsert(final FC_Account account) {

    return new PreparedStatementCreator() {
        @Override// w ww. ja  v  a2  s .co m
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(
                    "insert into FC_Account(" + "id_user_, balance)" + " values(?, ?)", RET_ID);
            ps.setInt(1, account.id_user_);
            ps.setBigDecimal(2, account.balance);
            return ps;
        }
    };
}