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:org.jabsorb.ext.DataList.java
/** * Create a DataList that is populated with data from a database. * The resulting List contains a Map for each row returned in the query. * The map is keyed by select column, and the values are the data values * Objects returned from the query.// w ww . j av a 2 s . c om * * @param conn connection to get data from * @param skip number of rows to skip before beginning to return results * @param pageSize number of results to return (even if more are available). * All results are returned if this is not greater than 0. * @param colSkip number of columns to skip in returned columnset * @param pageWidth number of columns to return (even if more are available). * All columns up to end (if colSkip>0) are returned if this * argument is not greater than 0. * @param sql SQL query to execute as a prepared statement * @param bindVars Array of bind variables for sql * @throws SQLException if something goes wrong while accessing the DB. */ public DataList(Connection conn, int skip, int pageSize, int colSkip, int pageWidth, String sql, Object[] bindVars) throws SQLException { super(); PreparedStatement p = null; try { p = conn.prepareStatement(sql); if (bindVars != null) { for (int i = 1; i <= bindVars.length; i++) { p.setObject(i, bindVars[i - 1]); } } read(skip, pageSize, colSkip, pageWidth, p.executeQuery()); } finally { if (p != null) { p.close(); } } }
From source file:org.openlogics.gears.jdbc.DataStore.java
protected PreparedStatement populatePreparedStatement(PreparedStatement preparedStatement, List params) throws SQLException { //preparedStatement.clearParameters(); for (int i = 0; i < params.size(); i++) { Object object = params.get(i); preparedStatement.setObject(i + 1, object); }//w w w .j av a 2s .c o m return preparedStatement; }
From source file:cz.jirutka.spring.data.jdbc.BaseJdbcRepository.java
private <S extends T> S insertWithAutoGeneratedKey(S entity, Map<String, Object> columns) { removeIdColumns(columns);/*from w ww .j a v a2 s . c o m*/ final String insertQuery = sqlGenerator.insert(table, columns); final Object[] queryParams = columns.values().toArray(); final GeneratedKeyHolder key = new GeneratedKeyHolder(); jdbcOps.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { String idColumnName = table.getPkColumns().get(0); PreparedStatement ps = con.prepareStatement(insertQuery, new String[] { idColumnName }); for (int i = 0; i < queryParams.length; ++i) { ps.setObject(i + 1, queryParams[i]); } return ps; } }, key); return postInsert(entity, key.getKey()); }
From source file:org.apache.cocoon.acting.DatabaseAuthenticatorAction.java
private PreparedStatement getAuthQuery(Connection conn, Configuration conf, Request req) { StringBuffer queryBuffer = new StringBuffer("SELECT "); StringBuffer queryBufferEnd = new StringBuffer(""); Configuration table = conf.getChild("table"); Configuration[] columns = table.getChildren("select"); try {/*from w w w .java2 s . co m*/ Object[] constraintValues = new Object[columns.length]; int constraints = 0; for (int i = 0; i < columns.length; i++) { String dbcol = columns[i].getAttribute("dbcol"); boolean nullable = false; if (i > 0) { queryBuffer.append(", "); } queryBuffer.append(dbcol); String requestParameter = columns[i].getAttribute("request-param", null); if (StringUtils.isNotBlank(requestParameter)) { String nullstr = columns[i].getAttribute("nullable", null); if (nullstr != null) { nullable = BooleanUtils.toBoolean(nullstr.trim()); } String constraintValue = req.getParameter(requestParameter); // if there is a request parameter name, // but not the value, we exit immediately do // that authorization fails authomatically if (StringUtils.isBlank(constraintValue) && !nullable) { getLogger().debug("DBAUTH: request-param " + requestParameter + " does not exist"); return null; } if (constraints > 0) { queryBufferEnd.append(" AND "); } queryBufferEnd.append(dbcol).append("= ?"); constraintValues[constraints++] = constraintValue; } } queryBuffer.append(" FROM "); queryBuffer.append(table.getAttribute("name")); if (StringUtils.isNotBlank(queryBufferEnd.toString())) { queryBuffer.append(" WHERE ").append(queryBufferEnd); } getLogger().debug("DBAUTH: query " + queryBuffer); PreparedStatement st = conn.prepareStatement(queryBuffer.toString()); for (int i = 0; i < constraints; i++) { getLogger() .debug("DBAUTH: parameter " + (i + 1) + " = [" + String.valueOf(constraintValues[i]) + "]"); st.setObject(i + 1, constraintValues[i]); } return st; } catch (Exception e) { getLogger().debug("DBAUTH: got exception: " + e); } return null; }
From source file:com.frostwire.database.sqlite.SQLiteDatabase.java
private PreparedStatement prepareStatement(Connection connection, String sql, Object... arguments) throws Exception { PreparedStatement statement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); if (arguments != null) { for (int i = 0; i < arguments.length; i++) { statement.setObject(i + 1, arguments[i]); }/*from w ww . j a v a2 s.c om*/ } return statement; }
From source file:och.comp.db.base.universal.UniversalQueries.java
private int deleteRows(DeleteRows update, Connection conn) throws SQLException { lastQuery.remove();/* ww w.j a v a 2 s .c om*/ StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM ").append(update.table); WhereCondition condition = update.whereCondition; appendWhereCondition(sb, condition); String q = sb.toString(); lastQuery.set(q); PreparedStatement ps = conn.prepareStatement(q); if (!isEmpty(condition)) { RowField<?>[] values = condition.values(); for (int i = 0; i < values.length; i++) { ps.setObject(i + 1, values[i].value); } } long start = System.currentTimeMillis(); logQueryStart(q); int out = ps.executeUpdate(); ps.close(); logQueryEnd(start); return out; }
From source file:org.oncoblocks.centromere.sql.GenericJdbcRepository.java
/** * {@link RepositoryOperations#insert}//from w w w . jav a2s . c o m */ public <S extends T> S insert(S entity) { SqlBuilder sqlBuilder = getSqlBuilder(); Map<String, Object> mappings = rowUnmapper.mapColumns(entity); final String sql = sqlBuilder.insert(mappings).toSql(); final Object[] values = sqlBuilder.getQueryParameterValues().toArray(); final String[] columns = mappings.keySet().toArray(new String[] {}); sqlBuilder.insert(mappings); S created = null; if (entity.getId() == null) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(sql, columns); for (int i = 0; i < values.length; i++) { preparedStatement.setObject(i + 1, values[i]); } return preparedStatement; } }, keyHolder); ID newId = (ID) keyHolder.getKey(); created = (S) findOne(newId); } else { jdbcTemplate.update(sql, values); created = entity; } return created; }
From source file:fr.aliacom.obm.common.addition.CommitedOperationDaoJdbcImpl.java
private PreparedStatement prepareInsertStatement(Connection con, CommitedElement commitedElement) throws SQLException { PreparedStatement ps = con.prepareStatement("INSERT INTO CommitedOperation " + "(commitedoperation_hash_client_id, commitedoperation_entity_id, commitedoperation_kind) " + "VALUES (?, ?, ?) "); int idx = 1;/* w w w.j a va2 s . c o m*/ try { ps.setString(idx++, commitedElement.getClientId()); ps.setInt(idx++, commitedElement.getEntityId().getId()); ps.setObject(idx++, getJdbcObject(commitedElement.getKind())); return ps; } catch (SQLException e) { ps.close(); throw e; } catch (RuntimeException e) { ps.close(); throw e; } }
From source file:org.eclipse.scada.ds.storage.jdbc.internal.JdbcStorageDaoBase64Impl.java
protected void insertNode(final ConnectionContext connectionContext, final DataNode node, final String data) throws SQLException { if (data == null) { return;//from w w w .ja v a2 s.c om } final PreparedStatement stmt = connectionContext.getConnection().prepareStatement(SQL_INSERT); final int len = data.length(); for (int i = 0; i <= len / this.chunkSize; i++) { int end = (i + 1) * this.chunkSize; if (end > len) { end = len; } final String chunk = data.substring(i * this.chunkSize, end); stmt.setObject(1, node.getId()); stmt.setObject(2, this.instanceId); stmt.setObject(3, i); stmt.setObject(4, chunk); stmt.addBatch(); } stmt.executeBatch(); }
From source file:com.espertech.esper.epl.db.PollExecStrategyDBQuery.java
private void setObject(PreparedStatement preparedStatement, int column, Object value) throws SQLException { // Allow java.util.Date conversion for JDBC drivers that don't provide this feature if (value instanceof Date) { value = new Timestamp(((Date) value).getTime()); } else if (value instanceof Calendar) { value = new Timestamp(((Calendar) value).getTimeInMillis()); }/*www . ja va 2 s.c om*/ preparedStatement.setObject(column, value); }