List of usage examples for java.sql PreparedStatement setBytes
void setBytes(int parameterIndex, byte x[]) throws SQLException;
From source file:com.runwaysdk.dataaccess.database.general.Oracle.java
/** * Add a blob attribute to a PreparedStatement and the given index. * * @param prepared The statement to add the blob to * @param index The index to add the blob to * @param current The current value of the blob * @param newBytes The new bytes to write to the blob * @return/* ww w .j av a 2s . com*/ * @throws SQLException */ private static int addBlobToStatement(PreparedStatement prepared, int index, Blob current, byte[] newBytes) throws SQLException { int written = 0; if (current == null) { prepared.setBytes(index, newBytes); written = newBytes.length; } else { written = current.setBytes(1, newBytes); prepared.setBlob(index, current); } return written; }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.AbstractApplicationDAOImpl.java
@Override public int addApplication(Application application, int tenantId) throws DeviceManagementDAOException { Connection conn;//from w ww. j a va2 s . com PreparedStatement stmt = null; ResultSet rs = null; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; int applicationId = -1; try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PLATFORM, CATEGORY, " + "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID, APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE, IS_ACTIVE) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, application.getName()); stmt.setString(2, application.getPlatform()); stmt.setString(3, application.getCategory()); stmt.setString(4, application.getVersion()); stmt.setString(5, application.getType()); stmt.setString(6, application.getLocationUrl()); stmt.setString(7, application.getImageUrl()); stmt.setInt(8, tenantId); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(application.getAppProperties()); stmt.setBytes(9, bao.toByteArray()); stmt.setString(10, application.getApplicationIdentifier()); stmt.setInt(11, application.getMemoryUsage()); stmt.setBoolean(12, application.isActive()); stmt.execute(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationId = rs.getInt(1); } return applicationId; } catch (SQLException e) { throw new DeviceManagementDAOException( "Error occurred while adding application '" + application.getName() + "'", e); } catch (IOException e) { throw new DeviceManagementDAOException("Error occurred while serializing application properties object", e); } finally { if (bao != null) { try { bao.close(); } catch (IOException e) { log.error("Error occurred while closing ByteArrayOutputStream", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { log.error("Error occurred while closing ObjectOutputStream", e); } } DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.SqlServerEngine.java
@Override protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps, final EntityEntry entry, boolean useAutoInc) throws DatabaseEngineException { int i = 1;/* w w w . j av a2 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, val); } } catch (Exception ex) { throw new DatabaseEngineException("Error while mapping variables to database", ex); } i++; } return i - 1; }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationDAOImpl.java
@Override public int addApplication(Application application, int tenantId) throws DeviceManagementDAOException { Connection conn;// w w w .ja v a2 s . c o m PreparedStatement stmt = null; ResultSet rs = null; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; int applicationId = -1; try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PLATFORM, CATEGORY, " + "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID, APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE, IS_ACTIVE) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, application.getName()); stmt.setString(2, application.getPlatform()); stmt.setString(3, application.getCategory()); stmt.setString(4, application.getVersion()); stmt.setString(5, application.getType()); stmt.setString(6, application.getLocationUrl()); stmt.setString(7, application.getImageUrl()); stmt.setInt(8, tenantId); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(application.getAppProperties()); stmt.setBytes(9, bao.toByteArray()); stmt.setString(10, application.getApplicationIdentifier()); stmt.setInt(11, application.getMemoryUsage()); stmt.setBoolean(12, application.isActive()); stmt.execute(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationId = rs.getInt(1); } return applicationId; } catch (SQLException e) { throw new DeviceManagementDAOException( "Error occurred while adding application '" + application.getName() + "'", e); } catch (IOException e) { throw new DeviceManagementDAOException("Error occurred while serializing application properties object", e); } finally { if (bao != null) { try { bao.close(); } catch (IOException e) { log.warn("Error occurred while closing ByteArrayOutputStream", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { log.warn("Error occurred while closing ObjectOutputStream", e); } } DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:chh.utils.db.source.common.JdbcClient.java
private void setPreparedStatementParams(PreparedStatement preparedStatement, List<Column> columnList) throws SQLException { int index = 1; for (Column column : columnList) { Class columnJavaType = Util.getJavaType(column.getSqlType()); if (column.getVal() == null) { preparedStatement.setNull(index, column.getSqlType()); } else if (columnJavaType.equals(String.class)) { preparedStatement.setString(index, (String) column.getVal()); } else if (columnJavaType.equals(Integer.class)) { preparedStatement.setInt(index, (Integer) column.getVal()); } else if (columnJavaType.equals(Double.class)) { preparedStatement.setDouble(index, (Double) column.getVal()); } else if (columnJavaType.equals(Float.class)) { preparedStatement.setFloat(index, (Float) column.getVal()); } else if (columnJavaType.equals(Short.class)) { preparedStatement.setShort(index, (Short) column.getVal()); } else if (columnJavaType.equals(Boolean.class)) { preparedStatement.setBoolean(index, (Boolean) column.getVal()); } else if (columnJavaType.equals(byte[].class)) { preparedStatement.setBytes(index, (byte[]) column.getVal()); } else if (columnJavaType.equals(Long.class)) { preparedStatement.setLong(index, (Long) column.getVal()); } else if (columnJavaType.equals(Date.class)) { preparedStatement.setDate(index, (Date) column.getVal()); } else if (columnJavaType.equals(Time.class)) { preparedStatement.setTime(index, (Time) column.getVal()); } else if (columnJavaType.equals(Timestamp.class)) { preparedStatement.setTimestamp(index, (Timestamp) column.getVal()); } else {/*from w w w .j a v a 2s . com*/ throw new RuntimeException( "Unknown type of value " + column.getVal() + " for column " + column.getColumnName()); } ++index; } }
From source file:org.wso2.carbon.device.mgt.core.archival.dao.impl.ArchivalDAOImpl.java
@Override public void moveOperationResponses() throws ArchivalDAOException { Statement stmt = null;/*from w w w. java 2 s. c o m*/ PreparedStatement stmt2 = null; Statement stmt3 = null; ResultSet rs = null; try { Connection conn = ArchivalSourceDAOFactory.getConnection(); String sql = "SELECT * FROM DM_DEVICE_OPERATION_RESPONSE WHERE OPERATION_ID IN " + "(SELECT ID FROM DM_ARCHIVED_OPERATIONS)"; stmt = this.createMemoryEfficientStatement(conn); rs = stmt.executeQuery(sql); Connection conn2 = ArchivalDestinationDAOFactory.getConnection(); sql = "INSERT INTO DM_DEVICE_OPERATION_RESPONSE_ARCH VALUES(?, ?, ?, ?, ?,?,?)"; stmt2 = conn2.prepareStatement(sql); int count = 0; while (rs.next()) { stmt2.setInt(1, rs.getInt("ID")); stmt2.setInt(2, rs.getInt("ENROLMENT_ID")); stmt2.setInt(3, rs.getInt("OPERATION_ID")); stmt2.setInt(4, rs.getInt("EN_OP_MAP_ID")); stmt2.setBytes(5, rs.getBytes("OPERATION_RESPONSE")); stmt2.setTimestamp(6, rs.getTimestamp("RECEIVED_TIMESTAMP")); stmt2.setTimestamp(7, this.currentTimestamp); stmt2.addBatch(); if (++count % batchSize == 0) { stmt2.executeBatch(); if (log.isDebugEnabled()) { log.debug("Executing batch " + count); } } } stmt2.executeBatch(); if (log.isDebugEnabled()) { log.debug(count + " [OPERATION_RESPONSES] Records copied to the archival table. Starting deletion"); } //try the deletion now sql = "DELETE FROM DM_DEVICE_OPERATION_RESPONSE WHERE OPERATION_ID IN (" + " SELECT ID FROM DM_ARCHIVED_OPERATIONS)"; stmt3 = conn.createStatement(); int affected = stmt3.executeUpdate(sql); if (log.isDebugEnabled()) { log.debug(affected + " Rows deleted"); } } catch (SQLException e) { throw new ArchivalDAOException("Error occurred while moving operations ", e); } finally { ArchivalDAOUtil.cleanupResources(stmt, rs); ArchivalDAOUtil.cleanupResources(stmt2); ArchivalDAOUtil.cleanupResources(stmt3); } }
From source file:com.feedzai.commons.sql.abstraction.engine.impl.MySqlEngine.java
@Override protected int entityToPreparedStatement(final DbEntity entity, final PreparedStatement ps, final EntityEntry entry, final boolean useAutoInc) throws DatabaseEngineException { int i = 1;// www . ja v a 2 s .c om 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, val); } } catch (Exception ex) { throw new DatabaseEngineException("Error while mapping variable s to database", ex); } i++; } return i - 1; }
From source file:com.cedarsoftware.ncube.NCubeManager.java
/** * Persist the passed in NCube//from ww w. ja v a2 s . c o m * * @param connection JDBC connection * @param ncube NCube to be persisted */ public static void createCube(Connection connection, String app, NCube ncube, String version) { validate(connection, app, version); if (ncube == null) { throw new IllegalArgumentException("NCube cannot be null when creating a new n-cube"); } validateCubeName(ncube.getName()); synchronized (cubeList) { PreparedStatement stmt = null; try { stmt = connection.prepareStatement( "SELECT n_cube_id AS \"id\" FROM n_cube WHERE app_cd = ? AND n_cube_nm = ? AND version_no_cd = ?"); stmt.setString(1, app); stmt.setString(2, ncube.getName()); stmt.setString(3, version); ResultSet rs = stmt.executeQuery(); if (rs.next()) { // NCube with same name and version number already exists. throw new IllegalStateException( "NCube '" + ncube.getName() + "' (" + version + ") already exists."); } else { // Do INSERT stmt.close(); stmt = connection.prepareStatement( "INSERT INTO n_cube (n_cube_id, app_cd, n_cube_nm, cube_value_bin, version_no_cd, create_dt, sys_effective_dt) VALUES (?, ?, ?, ?, ?, ?, ?)"); stmt.setLong(1, UniqueIdGenerator.getUniqueId()); stmt.setString(2, app); stmt.setString(3, ncube.getName()); String json = new JsonFormatter().format(ncube); // String json = JsonWriter.objectToJson(ncube); stmt.setBytes(4, json.getBytes("UTF-8")); stmt.setString(5, version); java.sql.Date now = new java.sql.Date(System.currentTimeMillis()); stmt.setDate(6, now); stmt.setDate(7, now); int rowCount = stmt.executeUpdate(); if (rowCount != 1) { throw new IllegalStateException("error saving new NCube: " + ncube.getName() + "', app: " + app + ", version: " + version + " (" + rowCount + " rows inserted, should be 1)"); } } addCube(ncube, version); } catch (IllegalStateException e) { throw e; } catch (Exception e) { String s = "Unable to save NCube: " + ncube.getName() + ", app: " + app + ", version: " + version + " to database"; LOG.error(s, e); throw new RuntimeException(s, e); } finally { jdbcCleanup(stmt); } } }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationDAOImpl.java
@Override public List<Integer> addApplications(List<Application> applications, int tenantId) throws DeviceManagementDAOException { Connection conn;//from ww w .j ava 2s. c om PreparedStatement stmt = null; ResultSet rs; ByteArrayOutputStream bao = null; ObjectOutputStream oos = null; List<Integer> applicationIds = new ArrayList<>(); try { conn = this.getConnection(); stmt = conn.prepareStatement("INSERT INTO DM_APPLICATION (NAME, PLATFORM, CATEGORY, " + "VERSION, TYPE, LOCATION_URL, IMAGE_URL, TENANT_ID,APP_PROPERTIES, APP_IDENTIFIER, MEMORY_USAGE, IS_ACTIVE) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", new String[] { "id" }); for (Application application : applications) { stmt.setString(1, application.getName()); stmt.setString(2, application.getPlatform()); stmt.setString(3, application.getCategory()); stmt.setString(4, application.getVersion()); stmt.setString(5, application.getType()); stmt.setString(6, application.getLocationUrl()); stmt.setString(7, application.getImageUrl()); stmt.setInt(8, tenantId); bao = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bao); oos.writeObject(application.getAppProperties()); stmt.setBytes(9, bao.toByteArray()); stmt.setString(10, application.getApplicationIdentifier()); stmt.setInt(11, application.getMemoryUsage()); stmt.setBoolean(12, application.isActive()); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationIds.add(rs.getInt(1)); } } return applicationIds; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while adding bulk application list", e); } catch (IOException e) { throw new DeviceManagementDAOException("Error occurred while serializing application properties object", e); } finally { if (bao != null) { try { bao.close(); } catch (IOException e) { log.warn("Error occurred while closing ByteArrayOutputStream", e); } } if (oos != null) { try { oos.close(); } catch (IOException e) { log.warn("Error occurred while closing ObjectOutputStream", e); } } DeviceManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:com.act.lcms.db.model.MS1ScanForWellAndMassCharge.java
protected void bindInsertOrUpdateParameters(PreparedStatement stmt, Integer plateId, Integer plateRow, Integer plateColumn, Boolean useSNR, String lcmsScanFileDir, String chemicalName, List<String> metlinIons, Map<String, List<XZ>> ionsToSpectra, Map<String, Double> ionsToIntegral, Map<String, Double> ionsToMax, Map<String, Double> ionsToLogSNR, Map<String, Double> ionsToAvgSignal, Map<String, Double> ionsToAvgAmbient, Map<String, Double> individualMaxIntensities, Double maxYAxis) throws SQLException, IOException { stmt.setInt(DB_FIELD.PLATE_ID.getInsertUpdateOffset(), plateId); stmt.setInt(DB_FIELD.PLATE_ROW.getInsertUpdateOffset(), plateRow); stmt.setInt(DB_FIELD.PLATE_COLUMN.getInsertUpdateOffset(), plateColumn); stmt.setBoolean(DB_FIELD.USE_SNR.getInsertUpdateOffset(), useSNR); stmt.setString(DB_FIELD.SCAN_FILE.getInsertUpdateOffset(), lcmsScanFileDir); stmt.setString(DB_FIELD.CHEMICAL_NAME.getInsertUpdateOffset(), chemicalName); stmt.setString(DB_FIELD.METLIN_IONS.getInsertUpdateOffset(), OBJECT_MAPPER.writeValueAsString(metlinIons)); stmt.setBytes(DB_FIELD.IONS_TO_SPECTRA.getInsertUpdateOffset(), serialize(ionsToSpectra)); stmt.setBytes(DB_FIELD.IONS_TO_INTEGRAL.getInsertUpdateOffset(), serialize(ionsToIntegral)); stmt.setBytes(DB_FIELD.IONS_TO_LOG_SNR.getInsertUpdateOffset(), serialize(ionsToLogSNR)); stmt.setBytes(DB_FIELD.IONS_TO_AVG_AMBIENT.getInsertUpdateOffset(), serialize(ionsToAvgAmbient)); stmt.setBytes(DB_FIELD.IONS_TO_AVG_SIGNAL.getInsertUpdateOffset(), serialize(ionsToAvgSignal)); stmt.setBytes(DB_FIELD.INDIVIDUAL_MAX_INTENSITIES.getInsertUpdateOffset(), serialize(individualMaxIntensities)); stmt.setBytes(DB_FIELD.IONS_TO_MAX.getInsertUpdateOffset(), serialize(ionsToMax)); stmt.setDouble(DB_FIELD.MAX_Y_AXIS.getInsertUpdateOffset(), maxYAxis); }