List of usage examples for java.sql PreparedStatement setBytes
void setBytes(int parameterIndex, byte x[]) throws SQLException;
From source file:com.feedzai.commons.sql.abstraction.engine.impl.OracleEngine.java
@Override protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps, final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException { int i = 1;// w ww. jav a 2 s. c o m for (DbColumn column : entity.getColumns()) { if (column.isAutoInc() && useAutoInc) { continue; } try { final Object val; if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) { val = column.getDefaultValue().getConstant(); } else { val = entry.get(column.getName()); } switch (column.getDbColumnType()) { case BLOB: ps.setBytes(i, objectToArray(val)); break; case CLOB: if (val == null) { ps.setNull(i, Types.CLOB); break; } if (val instanceof String) { StringReader sr = new StringReader((String) val); ps.setClob(i, sr); } else { throw new DatabaseEngineException("Cannot convert " + val.getClass().getSimpleName() + " to String. CLOB columns only accept Strings."); } break; case BOOLEAN: Boolean b = (Boolean) val; if (b == null) { ps.setObject(i, null); } else if (b) { ps.setObject(i, "1"); } else { ps.setObject(i, "0"); } break; default: ps.setObject(i, ensureNoUnderflow(val)); } } catch (Exception ex) { throw new DatabaseEngineException("Error while mapping variables to database", ex); } i++; } return i - 1; }
From source file:org.apache.jackrabbit.core.persistence.bundle.BundleDbPersistenceManager.java
/** * Sets the key parameters to the prepared statement, starting at * <code>pos</code> and returns the number of key parameters + pos. * * @param stmt the statement// w w w.ja v a 2s .c o m * @param uuid the uuid of the key * @param pos the position of the key parameter * @return the number of key parameters + <code>pos</code> * @throws SQLException if an SQL error occurs. */ protected int setKey(PreparedStatement stmt, UUID uuid, int pos) throws SQLException { if (getStorageModel() == SM_BINARY_KEYS) { stmt.setBytes(pos++, uuid.getRawBytes()); } else { stmt.setLong(pos++, uuid.getMostSignificantBits()); stmt.setLong(pos++, uuid.getLeastSignificantBits()); } return pos; }
From source file:org.apache.gora.sql.store.SqlStore.java
/** Serializes the field using Avro to a BLOB field */ protected void setField(PreparedStatement statement, Column column, Schema schema, int index, Object object) throws IOException, SQLException { OutputStream os = null;/*www .j ava 2 s .com*/ Blob blob = null; JdbcType type = column.getJdbcType(); switch (type) { case BLOB: blob = connection.createBlob(); os = blob.setBinaryStream(1); break; case BINARY: case VARBINARY: case LONGVARBINARY: os = new ByteBufferOutputStream(); break; } IOUtils.serialize(os, datumWriter, schema, object); os.close(); switch (type) { case BLOB: statement.setBlob(index, blob); break; case BINARY: case VARBINARY: statement.setBytes(index, IOUtils.getAsBytes(((ByteBufferOutputStream) os).getBufferList())); break; case LONGVARBINARY: statement.setBinaryStream(index, new ByteBufferInputStream(((ByteBufferOutputStream) os).getBufferList())); break; } }
From source file:com.opensymphony.module.propertyset.database.JDBCPropertySet.java
private void setValues(PreparedStatement ps, int type, String key, Object value) throws SQLException, PropertyException { // Patched by Edson Richter for MS SQL Server JDBC Support! String driverName;//from ww w.j a v a 2 s . co m try { driverName = ps.getConnection().getMetaData().getDriverName().toUpperCase(); } catch (Exception e) { driverName = ""; } ps.setNull(1, Types.VARCHAR); ps.setNull(2, Types.TIMESTAMP); // Patched by Edson Richter for MS SQL Server JDBC Support! // Oracle support suggestion also Michael G. Slack if ((driverName.indexOf("SQLSERVER") >= 0) || (driverName.indexOf("ORACLE") >= 0)) { ps.setNull(3, Types.BINARY); } else { ps.setNull(3, Types.BLOB); } ps.setNull(4, Types.FLOAT); ps.setNull(5, Types.NUMERIC); ps.setInt(6, type); ps.setString(7, globalKey); ps.setString(8, key); switch (type) { case PropertySet.BOOLEAN: Boolean boolVal = (Boolean) value; ps.setInt(5, boolVal.booleanValue() ? 1 : 0); break; case PropertySet.DATA: Data data = (Data) value; ps.setBytes(3, data.getBytes()); break; case PropertySet.DATE: Date date = (Date) value; ps.setTimestamp(2, new Timestamp(date.getTime())); break; case PropertySet.DOUBLE: Double d = (Double) value; ps.setDouble(4, d.doubleValue()); break; case PropertySet.INT: Integer i = (Integer) value; ps.setInt(5, i.intValue()); break; case PropertySet.LONG: Long l = (Long) value; ps.setLong(5, l.longValue()); break; case PropertySet.STRING: ps.setString(1, (String) value); break; default: throw new PropertyException("This type isn't supported!"); } }
From source file:com.pinterest.pinlater.backends.mysql.PinLaterMySQLBackend.java
@Override protected String enqueueSingleJob(String queueName, PinLaterJob job, int numAutoRetries) throws Exception { final long currentTimeMillis = System.currentTimeMillis(); Connection conn = null;/*from w ww .j a va 2s . c o m*/ PreparedStatement stmt = null; ResultSet rs = null; final ImmutableMap.Entry<String, MySQLDataSources> shard = getRandomEnqueueableShard(); try { conn = shard.getValue().getGeneralDataSource().getConnection(); String jobsTableName = MySQLBackendUtils.constructJobsTableName(queueName, shard.getKey(), job.getPriority()); stmt = conn.prepareStatement(String.format(MySQLQueries.ENQUEUE_INSERT, jobsTableName), Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, PinLaterJobState.PENDING.getValue()); stmt.setInt(2, job.getNumAttemptsAllowed()); stmt.setInt(3, job.getNumAttemptsAllowed()); stmt.setString(4, job.getCustomStatus()); stmt.setTimestamp(5, new Timestamp(currentTimeMillis)); stmt.setTimestamp(6, new Timestamp( job.isSetRunAfterTimestampMillis() ? job.getRunAfterTimestampMillis() : currentTimeMillis)); stmt.setBytes(7, job.getBody()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); rs.next(); return new PinLaterJobDescriptor(queueName, shard.getKey(), job.getPriority(), rs.getLong(1)) .toString(); } catch (SQLException e) { boolean shouldRetry = checkExceptionIsRetriable(e, shard.getKey(), "enqueue"); if (shouldRetry && numAutoRetries > 0) { // Retry the enqueue, potentially on a different shard. Stats.incr("enqueue-failures-retry"); return enqueueSingleJob(queueName, job, numAutoRetries - 1); } // Out of retries, throw the exception. Wrap it into a PinLaterException if the exception // is recognized and return the appropriate error code. if (MySQLBackendUtils.isDatabaseDoesNotExistException(e)) { throw new PinLaterException(ErrorCode.QUEUE_NOT_FOUND, "Queue not found: " + queueName); } throw e; } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(stmt); JdbcUtils.closeConnection(conn); } }
From source file:AIR.Common.DB.AbstractDLL.java
protected void executePreparedStatementBatch(SQLConnection connection, String query, List<Map<Integer, Object>> paramsList) throws ReturnStatusException { PreparedStatement prepStmt = null; try {/*from w w w . ja va2s . c o m*/ boolean preexistingAutoCommitMode = connection.getAutoCommit(); connection.setAutoCommit(false); prepStmt = connection.prepareStatement(query); if (paramsList != null) { for (Map<Integer, Object> params : paramsList) { Iterator<Entry<Integer, Object>> param = params.entrySet().iterator(); while (param.hasNext()) { Entry<Integer, Object> entry = param.next(); if (entry.getValue() instanceof String) { prepStmt.setString(entry.getKey(), entry.getValue().toString()); } else if (entry.getValue() instanceof Integer) { prepStmt.setInt(entry.getKey(), (Integer) entry.getValue()); } else if (entry.getValue() instanceof Date) { prepStmt.setString(entry.getKey(), String.format("%s", AbstractDateUtilDll .getDateAsFormattedMillisecondsString((Date) entry.getValue()))); } else if (entry.getValue() instanceof UUID) { String newStr = entry.getValue().toString().replaceAll("-", ""); prepStmt.setBytes(entry.getKey(), DatatypeConverter.parseHexBinary(newStr)); } else if (entry.getValue() instanceof Boolean) { prepStmt.setBoolean(entry.getKey(), (Boolean) entry.getValue()); } } prepStmt.addBatch(); } } prepStmt.executeBatch(); prepStmt.close(); connection.commit(); // reset autocommit. connection.setAutoCommit(preexistingAutoCommitMode); } catch (SQLException exp) { throw new ReturnStatusException(exp); } finally { if (prepStmt != null) try { prepStmt.close(); } catch (SQLException e) { } } }
From source file:org.apache.ode.daohib.bpel.hobj.GZipDataType.java
/** Write an instance of the mapped class to a prepared statement. */ public void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException { byte[] buf = (byte[]) value; if (buf != null) { synchronized (STATS_LOCK) { if (_totalBytesBefore > Integer.MAX_VALUE) { // prevent overflow - renormalize to percent value _totalBytesAfter = _totalBytesAfter * 100 / _totalBytesBefore; _totalBytesBefore = 100; }//from w w w. j a va 2 s .co m _totalBytesBefore += buf.length; } // only try to zip if we have more than 100 bytes if (buf != null && buf.length > 100 && _compressionEnabled) { ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length); for (int i = 0; i < GZIP_PREFIX.length; i++) { baos.write(GZIP_PREFIX[i]); } gzip((byte[]) value, baos); byte[] zipped = baos.toByteArray(); // only use zipped representation if we gain 2% or more if (zipped.length * 100 / buf.length < 99) { buf = zipped; } } synchronized (STATS_LOCK) { _totalBytesAfter += buf.length; } if (log.isDebugEnabled()) { long now = System.currentTimeMillis(); if (_lastLogTime + 5000 < now) { log.debug("Average compression ratio: " + (_totalBytesAfter * 100 / _totalBytesBefore) + "%"); _lastLogTime = now; } } } st.setBytes(index, buf); }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.DB2Engine.java
@Override protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps, final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException { int i = 1;//from w ww . j av a 2s .c o m for (DbColumn column : entity.getColumns()) { if (column.isAutoInc() && useAutoInc) { continue; } try { final Object val; if (column.isDefaultValueSet() && !entry.containsKey(column.getName())) { val = column.getDefaultValue().getConstant(); } else { val = entry.get(column.getName()); } switch (column.getDbColumnType()) { /* * CLOB and BLOB are handled the same way in DB2 since CLOB is not supported. */ case CLOB: case BLOB: ps.setBytes(i, objectToArray(val)); break; case BOOLEAN: Boolean b = (Boolean) val; if (b == null) { ps.setObject(i, null); } else if (b) { ps.setObject(i, "1"); } else { ps.setObject(i, "0"); } break; default: ps.setObject(i, val); } } catch (Exception ex) { throw new DatabaseEngineException("Error while mapping variables to database", ex); } i++; } return i - 1; }
From source file:org.opencms.setup.CmsSetupDb.java
/** * Creates and executes a database statment from a String.<p> * * @param query the query to execute//from ww w . j a v a 2 s. c o m * @param replacer the replacements to perform in the script * @param params the list of parameters for the statement * * @return the result set of the query * * @throws SQLException if something goes wrong */ public int updateSqlStatement(String query, Map<String, String> replacer, List<Object> params) throws SQLException { String queryToExecute = query; // Check if a map of replacements is given if (replacer != null) { queryToExecute = replaceTokens(query, replacer); } int result; PreparedStatement stmt = null; stmt = m_con.prepareStatement(queryToExecute); try { // Check the params if (params != null) { for (int i = 0; i < params.size(); i++) { Object item = params.get(i); // Check if the parameter is a string if (item instanceof String) { stmt.setString(i + 1, (String) item); } if (item instanceof Integer) { Integer number = (Integer) item; stmt.setInt(i + 1, number.intValue()); } if (item instanceof Long) { Long longNumber = (Long) item; stmt.setLong(i + 1, longNumber.longValue()); } // If item is none of types above set the statement to use the bytes if (!(item instanceof Integer) && !(item instanceof String) && !(item instanceof Long)) { try { stmt.setBytes(i + 1, CmsDataTypeUtil.dataSerialize(item)); } catch (IOException e) { e.printStackTrace(); } } } } if (!queryToExecute.startsWith("UPDATE CMS_ONLINE_STRUCTURE SET STRUCTURE_VERSION") && !queryToExecute.startsWith("UPDATE CMS_OFFLINE_STRUCTURE SET STRUCTURE_VERSION")) { System.out.println("executing query: " + queryToExecute); if ((params != null) && !params.isEmpty()) { System.out.println("params: " + params); } } result = stmt.executeUpdate(); } finally { stmt.close(); } return result; }
From source file:org.infoglue.cms.controllers.kernel.impl.simple.InstallationController.java
/** * This method issues special command to the db. I had to build my own adoption of sql to make this feature. * @throws Exception //from w ww. ja v a 2s .co m */ protected void issueSpecialCommand(Connection conn, String sql) throws Exception { logger.warn("Command:" + sql); try { String tableName = null; String columnName = null; String image = null; String idColumn = null; String idValue = null; StringTokenizer st = new StringTokenizer(sql, " "); int i = 0; while (st.hasMoreTokens()) { String part = st.nextToken(); //Logger.logInfo("Part: " + part); if (i == 2) tableName = part; if (i == 4) columnName = part; if (i == 6) image = part; if (i == 8) idColumn = part; if (i == 10) idValue = part; i++; } File file = new File(image); FileInputStream fis = new FileInputStream(file); byte[] imageByteArray = new byte[(int) file.length()]; fis.read(imageByteArray); sql = "UPDATE " + tableName + " SET " + columnName + " = ? WHERE " + idColumn + " = " + idValue + ""; //Logger.logInfo("newSQL:" + newSQL); PreparedStatement ps = conn.prepareStatement(sql); ps.setBytes(1, imageByteArray); ps.executeUpdate(); } catch (Exception ex) { logger.error("Command failed: " + ex.getMessage() + "\n" + "SQL: " + sql); throw ex; } }