List of usage examples for java.sql PreparedStatement setObject
void setObject(int parameterIndex, Object x) throws SQLException;
Sets the value of the designated parameter using the given object.
From source file:com.quinsoft.zeidon.dbhandler.StandardJdbcTranslator.java
@Override public String bindAttributeValue(PreparedStatement ps, Object value, int idx) { try {// ww w . j a v a 2 s . com if (value instanceof DateTime) { DateTime d = (DateTime) value; ps.setObject(idx, new Date(d.getMillis())); } else if (value instanceof GeneratedKey) { GeneratedKey k = (GeneratedKey) value; ps.setObject(idx, k.getNativeValue()); } else { ps.setObject(idx, value); } if (value == null) return "<null>"; return value.toString(); } catch (Exception e) { String className = value == null ? "<null>" : value.getClass().getCanonicalName(); throw ZeidonException.wrapException(e).appendMessage("Col index: %d\nValue %s\nClass: %s", idx, value, className); } }
From source file:mayoapp.migrations.V0400_2024__move_order_items_to_own_table.java
@Override public void migrate(Connection connection) throws Exception { connection.setAutoCommit(false);/*from www . j ava 2 s .c om*/ Statement queryStatement = connection.createStatement(); ResultSet data = queryStatement.executeQuery("SELECT * from purchase_order"); List<Order> orders = Lists.newArrayList(); List<OrderItem> orderItems = Lists.newArrayList(); ObjectMapper mapper = new ObjectMapper(); while (data.next()) { Order order = new Order(); order.setId((UUID) data.getObject("entity_id")); String orderDataString = data.getString("order_data"); Map<String, Object> orderData = mapper.readValue(orderDataString, new TypeReference<Map<String, Object>>() { }); List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items"); for (Map<String, Object> item : items) { OrderItem orderItem = new OrderItem(); orderItem.setId(UUID.randomUUID()); orderItem.setOrderId(order.getId()); if (item.containsKey("id") && String.class.isAssignableFrom(item.get("id").getClass())) { orderItem.setPurchasableId(UUID.fromString((String) item.get("id"))); } orderItem.setType((String) item.get("type")); orderItem.setTitle((String) item.get("title")); orderItem.setQuantity(((Integer) item.get("quantity")).longValue()); orderItem.setUnitPrice(BigDecimal.valueOf((Double) item.get("unitPrice"))); orderItem.setItemTotal(BigDecimal.valueOf((Double) item.get("itemTotal"))); if (item.containsKey("vatRate")) { orderItem.setVatRate(BigDecimal.valueOf((Double) item.get("vatRate"))); } if (item.containsKey("addons")) { orderItem.addData("addons", convertAddonsToMap((List<Map<String, Object>>) item.get("addons"))); } orderItems.add(orderItem); } orderData.remove("items"); order.setOrderData(orderData); orders.add(order); } queryStatement.close(); // 1. Update orders PreparedStatement updateOrders = connection .prepareStatement("UPDATE purchase_order SET order_data = CAST (? AS json) WHERE entity_id =?"); for (Order order : orders) { updateOrders.setObject(1, mapper.writeValueAsString(order.getOrderData())); updateOrders.setObject(2, order.getId()); updateOrders.addBatch(); } updateOrders.executeBatch(); // 2. Insert items PreparedStatement insertItems = connection.prepareStatement( "INSERT INTO purchase_order_item (id, order_id, purchasable_id, type, title, quantity, unit_price, " + "item_total, vat_rate, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST (? as json))"); for (OrderItem item : orderItems) { insertItems.setObject(1, item.getId()); insertItems.setObject(2, item.getOrderId()); insertItems.setObject(3, item.getPurchasableId()); insertItems.setString(4, item.getType()); insertItems.setString(5, item.getTitle()); insertItems.setLong(6, item.getQuantity()); insertItems.setBigDecimal(7, item.getUnitPrice()); insertItems.setBigDecimal(8, item.getItemTotal()); insertItems.setBigDecimal(9, item.getVatRate()); insertItems.setString(10, mapper.writeValueAsString(item.getData())); insertItems.addBatch(); } insertItems.executeBatch(); }
From source file:com.github.woozoo73.test.JdbcProfilingTest.java
private ResultSet executeQuery(String sql, Object[] args) { ResultSet rs = null;//w ww . j av a2 s . c o m Connection con = null; PreparedStatement ps = null; try { con = getConnection(); ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } rs = ps.executeQuery(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (ps != null) { try { ps.close(); } catch (SQLException e) { } } if (con != null) { try { con.close(); } catch (SQLException e) { } } } return rs; }
From source file:org.castor.jpa.functional.AbstractSpringBaseTest.java
/** * This helper method executes a prepared statement including the given * parameters./*from w w w .j av a 2 s. c o m*/ * * @param query * is a native SQL query. * @param parameters * is an array of {@link Object}s used as parameters. * @return the same as {@link PreparedStatement#executeUpdate()}. * @throws SQLException * in case execution fails. */ protected final int executeUpdate(String query, Object... parameters) throws SQLException { try { Connection connection = this.dataSource.getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(query); for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) { Object parameter = parameters[parameterIndex]; preparedStatement.setObject(parameterIndex + 1, parameter); } // Execute query. int numberAffected = preparedStatement.executeUpdate(); // Release resources. preparedStatement.close(); connection.close(); return numberAffected; } catch (SQLException e) { throw e; } }
From source file:org.metis.jdbc.PreparedStmntCreator.java
private void bindObjects(PreparedStatement ps) throws SQLException { // bind the corresponding objects (if any) if (bindObs != null) { LOG.debug("setValues: binding this many objects " + bindObs.length); for (int i = 0; i < bindObs.length; i++) { try { ps.setObject(i + 1, bindObs[i]); } catch (Exception e) { String eStr = "setValues: caught this exception [" + e.getLocalizedMessage() + "], when calling setObject for [" + bindObs[i].toString() + "]"; LOG.error(eStr);/*from w w w .j a va 2 s . com*/ throw new SQLException(eStr); } } } return; }
From source file:com.redhat.victims.database.VictimsSQL.java
/** * Helper function to set the values given, to a {@link PreparedStatement}, * in the order in which they are given. * * @param ps//from www. ja v a 2 s. c o m * @param objects * @throws SQLException */ protected void setObjects(PreparedStatement ps, Object... objects) throws SQLException { int index = 1; for (Object obj : objects) { ps.setObject(index, obj); index++; } }
From source file:org.danann.cernunnos.sql.PhraseParameterPreparedStatementSetter.java
public final void setValues(PreparedStatement ps) throws SQLException { if (this.logger.isDebugEnabled()) { this.logger.debug("Setting parameters " + this.parameters + " on prepared statement " + ps); }/* w ww . ja va 2 s . c o m*/ int parameterIndex = 0; for (final Phrase parameterPhrase : this.parameters) { final Object parameter = parameterPhrase.evaluate(this.req, this.res); ps.setObject(++parameterIndex, parameter); } }
From source file:be.bittich.dynaorm.repository.GenericDynaRepository.java
/** * execute a query sql and returns a resultset * @param sql/*from w w w .j a va2s . c o m*/ * @param params * @return * @throws SQLException */ @Override public ResultSet executeQuerySQL(String sql, Object... params) throws SQLException { Connection conn = runner.getDataSource().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { stmt.setObject(i + 1, params[i]); } return stmt.executeQuery(); }
From source file:be.bittich.dynaorm.repository.GenericDynaRepository.java
/** * Execute a query sql and return an int * @param sql// ww w.jav a 2 s . c om * @param params * @return * @throws SQLException */ @Override public int executeQueryUpdateSQL(String sql, Object... params) throws SQLException { Connection conn = runner.getDataSource().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { stmt.setObject(i + 1, params[i]); } return stmt.executeUpdate(); }
From source file:de.static_interface.reallifeplugin.database.AbstractTable.java
public ResultSet executeQuery(String sql, @Nullable Object... paramObjects) throws SQLException { sql = sql.replaceAll("\\Q{TABLE}\\E", getName()); try {/*from w w w . j a v a2 s . c om*/ PreparedStatement statment = db.getConnection().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); if (paramObjects != null) { int i = 1; for (Object s : paramObjects) { statment.setObject(i, s); i++; } } return statment.executeQuery(); } catch (SQLException e) { ReallifeMain.getInstance().getLogger() .severe("Couldn't execute SQL query: " + sqlToString(sql, paramObjects)); throw e; } }