List of usage examples for java.sql PreparedStatement setBytes
void setBytes(int parameterIndex, byte x[]) throws SQLException;
From source file:egovframework.rte.bat.core.item.database.support.EgovMethodMapItemPreparedStatementSetter.java
/** * params ? ? sqlType PreparedStatement? ?? *//*from w w w . j a v a 2 s.c o m*/ public void setValues(T item, PreparedStatement ps, String[] params, String[] sqlTypes, Map<String, Method> methodMap) throws SQLException { EgovReflectionSupport<T> reflector = new EgovReflectionSupport<T>(); for (int i = 0; i < params.length; i++) { try { if (sqlTypes[i].equals("String")) { ps.setString(i + 1, (String) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("int")) { ps.setInt(i + 1, (Integer) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("double")) { ps.setDouble(i + 1, (Double) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("Date")) { ps.setDate(i + 1, (Date) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("byte")) { ps.setByte(i + 1, (Byte) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("short")) { ps.setShort(i + 1, (Short) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("boolean")) { ps.setBoolean(i + 1, (Boolean) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("long")) { ps.setLong(i + 1, (Long) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("Float")) { ps.setFloat(i + 1, (Float) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("BigDecimal")) { ps.setBigDecimal(i + 1, (BigDecimal) reflector.invokeGettterMethod(item, params[i], methodMap)); } else if (sqlTypes[i].equals("byte[]")) { ps.setBytes(i + 1, (byte[]) reflector.invokeGettterMethod(item, params[i], methodMap)); } else { throw new SQLException(); } } catch (IllegalArgumentException e) { ReflectionUtils.handleReflectionException(e); } } }
From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.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. java2s . c o 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!"); } if (valueMap == null) valueMap = new HashMap(); if (typeMap == null) typeMap = new HashMap(); valueMap.put(key, value); typeMap.put(key, new Integer(type)); }
From source file:org.sakaiproject.assignment.impl.conversion.CombineDuplicateSubmissionsConversionHandler.java
public boolean convertSource(String id, Object source, PreparedStatement updateRecord) throws SQLException { List<String> xml = (List<String>) source; SortedSet<String> identifiers = new TreeSet<String>(); List<AssignmentSubmissionAccess> saxlist = new ArrayList<AssignmentSubmissionAccess>(); for (int i = 0; i < xml.size(); i++) { AssignmentSubmissionAccess sax = new AssignmentSubmissionAccess(); saxlist.add(sax);//from w w w . j av a2 s . c o m try { sax.parse(xml.get(i)); identifiers.add(sax.getId()); } catch (Exception e1) { log.warn("Failed to parse {}[{}]{}", id, xml, e1); // return false; } } for (int i = saxlist.size() - 1; i > 0; i--) { saxlist.set(i - 1, combineItems(saxlist.get(i), saxlist.get(i - 1))); } if (saxlist.size() > 0) { AssignmentSubmissionAccess result = saxlist.get(0); String xml0 = result.toXml(); String submitTime0 = result.getDatesubmitted(); String submitted0 = result.getSubmitted(); String graded0 = result.getGraded(); String id0 = result.getId(); log.info("updating \"{} revising XML", id0); if (getDbDriver().indexOf("mysql") != -1) { // see http://bugs.sakaiproject.org/jira/browse/SAK-1737 // MySQL setCharacterStream() is broken and truncates UTF-8 // international characters sometimes. So use setBytes() // instead (just for MySQL). try { updateRecord.setBytes(1, xml0.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.info("{}{}", e.getMessage(), xml0); } } else { updateRecord.setCharacterStream(1, new StringReader(xml0), xml0.length()); } updateRecord.setString(2, submitTime0); updateRecord.setString(3, submitted0); updateRecord.setString(4, graded0); updateRecord.setString(5, id0); return true; } else { return false; } }
From source file:org.sakaiproject.assignment.impl.conversion.impl.CombineDuplicateSubmissionsConversionHandler.java
public boolean convertSource(String id, Object source, PreparedStatement updateRecord) throws SQLException { List<String> xml = (List<String>) source; SortedSet<String> identifiers = new TreeSet<String>(); List<AssignmentSubmissionAccess> saxlist = new ArrayList<AssignmentSubmissionAccess>(); for (int i = 0; i < xml.size(); i++) { AssignmentSubmissionAccess sax = new AssignmentSubmissionAccess(); saxlist.add(sax);/*from w w w.j a v a 2s. c o m*/ try { sax.parse(xml.get(i)); identifiers.add(sax.getId()); } catch (Exception e1) { log.warn("Failed to parse " + id + "[" + xml + "]", e1); // return false; } } for (int i = saxlist.size() - 1; i > 0; i--) { saxlist.set(i - 1, combineItems(saxlist.get(i), saxlist.get(i - 1))); } if (saxlist.size() > 0) { AssignmentSubmissionAccess result = saxlist.get(0); String xml0 = result.toXml(); String submitTime0 = result.getDatesubmitted(); String submitted0 = result.getSubmitted(); String graded0 = result.getGraded(); String id0 = result.getId(); log.info("updating \"" + id0 + " revising XML"); if (getDbDriver().indexOf("mysql") != -1) { // see http://bugs.sakaiproject.org/jira/browse/SAK-1737 // MySQL setCharacterStream() is broken and truncates UTF-8 // international characters sometimes. So use setBytes() // instead (just for MySQL). try { updateRecord.setBytes(1, xml0.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.info(e.getMessage() + xml0); } } else { updateRecord.setCharacterStream(1, new StringReader(xml0), xml0.length()); } updateRecord.setString(2, submitTime0); updateRecord.setString(3, submitted0); updateRecord.setString(4, graded0); updateRecord.setString(5, id0); return true; } else { return false; } }
From source file:com.cedarsoftware.ncube.NCubeManager.java
/** * This API creates a SNAPSHOT set of cubes by copying all of * the RELEASE ncubes that match the oldVersion and app to * the new version in SNAPSHOT mode. Basically, it duplicates * an entire set of NCubes and places a new version label on them, * in SNAPSHOT status./*www .j av a 2 s. c o m*/ */ public static int createSnapshotCubes(Connection connection, String app, String relVersion, String newSnapVer) { validate(connection, app, relVersion); validateVersion(newSnapVer); if (relVersion.equals(newSnapVer)) { throw new IllegalArgumentException( "New SNAPSHOT version " + relVersion + " cannot be the same as the RELEASE version."); } synchronized (cubeList) { PreparedStatement stmt0 = null; PreparedStatement stmt1 = null; PreparedStatement stmt2 = null; try { stmt0 = connection .prepareStatement("SELECT n_cube_id FROM n_cube WHERE app_cd = ? AND version_no_cd = ?"); stmt0.setString(1, app); stmt0.setString(2, newSnapVer); ResultSet rs = stmt0.executeQuery(); if (rs.next()) { throw new IllegalStateException("New SNAPSHOT Version specified (" + newSnapVer + ") matches an existing version. Specify new SNAPSHOT version that does not exist."); } rs.close(); stmt1 = connection.prepareStatement( "SELECT n_cube_nm, cube_value_bin, create_dt, update_dt, create_hid, update_hid, version_no_cd, status_cd, sys_effective_dt, sys_expiration_dt, business_effective_dt, business_expiration_dt, app_cd, test_data_bin, notes_bin\n" + "FROM n_cube\n" + "WHERE app_cd = ? AND version_no_cd = ? AND status_cd = '" + ReleaseStatus.RELEASE + "'"); stmt1.setString(1, app); stmt1.setString(2, relVersion); rs = stmt1.executeQuery(); stmt2 = connection.prepareStatement( "INSERT INTO n_cube (n_cube_id, n_cube_nm, cube_value_bin, create_dt, update_dt, create_hid, update_hid, version_no_cd, status_cd, sys_effective_dt, sys_expiration_dt, business_effective_dt, business_expiration_dt, app_cd, test_data_bin, notes_bin)\n" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); int count = 0; while (rs.next()) { count++; stmt2.setLong(1, UniqueIdGenerator.getUniqueId()); stmt2.setString(2, rs.getString("n_cube_nm")); stmt2.setBytes(3, rs.getBytes("cube_value_bin")); stmt2.setDate(4, new java.sql.Date(System.currentTimeMillis())); stmt2.setDate(5, new java.sql.Date(System.currentTimeMillis())); stmt2.setString(6, rs.getString("create_hid")); stmt2.setString(7, rs.getString("update_hid")); stmt2.setString(8, newSnapVer); stmt2.setString(9, ReleaseStatus.SNAPSHOT.name()); stmt2.setDate(10, rs.getDate("sys_effective_dt")); stmt2.setDate(11, rs.getDate("sys_expiration_dt")); stmt2.setDate(12, rs.getDate("business_effective_dt")); stmt2.setDate(13, rs.getDate("business_expiration_dt")); stmt2.setString(14, rs.getString("app_cd")); stmt2.setBytes(15, rs.getBytes("test_data_bin")); stmt2.setBytes(16, rs.getBytes("notes_bin")); stmt2.executeUpdate(); } return count; } catch (IllegalStateException e) { throw e; } catch (Exception e) { String s = "Unable to create SNAPSHOT NCubes for app: " + app + ", version: " + newSnapVer + ", due to an error: " + e.getMessage(); LOG.error(s, e); throw new RuntimeException(s, e); } finally { jdbcCleanup(stmt0); jdbcCleanup(stmt1); jdbcCleanup(stmt2); } } }
From source file:org.ensembl.healthcheck.util.ConnectionBasedSqlTemplateImpl.java
private void bindParamsToPreparedStatement(PreparedStatement st, Object[] arguments) throws SQLException { int i = 0;/*from www. java 2 s . c o m*/ if (arguments != null) { for (Object arg : arguments) { i++; if (arg == null) { st.setNull(i, Types.NULL); } else if (arg instanceof String) { st.setString(i, (String) arg); } else if (arg instanceof Integer) { st.setInt(i, (Integer) arg); } else if (arg instanceof Boolean) { st.setBoolean(i, (Boolean) arg); } else if (arg instanceof Short) { st.setShort(i, (Short) arg); } else if (arg instanceof Date) { st.setTimestamp(i, new java.sql.Timestamp(((Date) arg).getTime())); } else if (arg instanceof java.sql.Date) { st.setDate(i, new java.sql.Date(((Date) arg).getTime())); } else if (arg instanceof Double) { st.setDouble(i, (Double) arg); } else if (arg instanceof Long) { st.setLong(i, (Long) arg); } else if (arg instanceof BigDecimal) { st.setObject(i, arg); } else if (arg instanceof BigInteger) { st.setObject(i, arg); } else { // Object try { ByteArrayOutputStream bytesS = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bytesS); out.writeObject(arg); out.close(); byte[] bytes = bytesS.toByteArray(); bytesS.close(); st.setBytes(i, bytes); } catch (IOException e) { throw new SQLException( "Could not serialize object " + arg + " for use in a PreparedStatement "); } } } } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public Policy addPolicyToDevice(List<Device> devices, Policy policy) throws PolicyManagerDAOException { Connection conn;// ww w. j a va 2 s . c o m PreparedStatement stmt = null; try { conn = this.getConnection(); String query = "INSERT INTO DM_DEVICE_POLICY (DEVICE_ID, POLICY_ID, ENROLMENT_ID, DEVICE) VALUES (?, ?, " + "?, ?)"; stmt = conn.prepareStatement(query); for (Device device : devices) { stmt.setInt(1, device.getId()); stmt.setInt(2, policy.getId()); stmt.setInt(3, device.getEnrolmentInfo().getId()); stmt.setBytes(4, PolicyManagerUtil.getBytes(device)); stmt.addBatch(); } stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException( "Error occurred while adding the device ids with policy to " + "database", e); } catch (IOException e) { throw new PolicyManagerDAOException("Error occurred while getting the byte array from device.", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } return policy; }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public void updateEffectivePolicyToDevice(int deviceId, int enrolmentId, Policy policy) throws PolicyManagerDAOException { Connection conn;/*from ww w. j av a 2 s. co m*/ PreparedStatement stmt = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "UPDATE DM_DEVICE_POLICY_APPLIED SET POLICY_ID = ?, POLICY_CONTENT = ?, UPDATED_TIME = ?, " + "APPLIED = ? WHERE DEVICE_ID = ? AND TENANT_ID = ? AND ENROLMENT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setInt(1, policy.getId()); stmt.setBytes(2, PolicyManagerUtil.getBytes(policy)); stmt.setTimestamp(3, currentTimestamp); stmt.setBoolean(4, false); stmt.setInt(5, deviceId); stmt.setInt(6, tenantId); stmt.setInt(7, enrolmentId); stmt.executeUpdate(); } catch (SQLException | IOException e) { throw new PolicyManagerDAOException( "Error occurred while updating the evaluated feature list " + "to device", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java
@Override public void addEffectivePolicyToDevice(int deviceId, int enrolmentId, Policy policy) throws PolicyManagerDAOException { Connection conn;/*w ww .j a v a 2s . c o m*/ PreparedStatement stmt = null; Timestamp currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); try { conn = this.getConnection(); String query = "INSERT INTO DM_DEVICE_POLICY_APPLIED (DEVICE_ID, POLICY_ID, POLICY_CONTENT, " + "CREATED_TIME, UPDATED_TIME, TENANT_ID, ENROLMENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(query); stmt.setInt(1, deviceId); stmt.setInt(2, policy.getId()); stmt.setBytes(3, PolicyManagerUtil.getBytes(policy)); stmt.setTimestamp(4, currentTimestamp); stmt.setTimestamp(5, currentTimestamp); stmt.setInt(6, tenantId); stmt.setInt(7, enrolmentId); stmt.executeUpdate(); } catch (SQLException | IOException e) { throw new PolicyManagerDAOException("Error occurred while adding the evaluated feature list to device", e); } finally { PolicyManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:org.waarp.common.database.data.AbstractDbData.java
/** * Set Value into PreparedStatement/*from w w w .ja v a 2s.c o m*/ * * @param ps * @param value * @param rank * >= 1 * @throws WaarpDatabaseSqlException */ static public void setTrueValue(PreparedStatement ps, DbValue value, int rank) throws WaarpDatabaseSqlException { try { switch (value.type) { case Types.VARCHAR: if (value.value == null) { ps.setNull(rank, Types.VARCHAR); break; } ps.setString(rank, (String) value.value); break; case Types.LONGVARCHAR: if (value.value == null) { ps.setNull(rank, Types.LONGVARCHAR); break; } ps.setString(rank, (String) value.value); break; case Types.BIT: if (value.value == null) { ps.setNull(rank, Types.BIT); break; } ps.setBoolean(rank, (Boolean) value.value); break; case Types.TINYINT: if (value.value == null) { ps.setNull(rank, Types.TINYINT); break; } ps.setByte(rank, (Byte) value.value); break; case Types.SMALLINT: if (value.value == null) { ps.setNull(rank, Types.SMALLINT); break; } ps.setShort(rank, (Short) value.value); break; case Types.INTEGER: if (value.value == null) { ps.setNull(rank, Types.INTEGER); break; } ps.setInt(rank, (Integer) value.value); break; case Types.BIGINT: if (value.value == null) { ps.setNull(rank, Types.BIGINT); break; } ps.setLong(rank, (Long) value.value); break; case Types.REAL: if (value.value == null) { ps.setNull(rank, Types.REAL); break; } ps.setFloat(rank, (Float) value.value); break; case Types.DOUBLE: if (value.value == null) { ps.setNull(rank, Types.DOUBLE); break; } ps.setDouble(rank, (Double) value.value); break; case Types.VARBINARY: if (value.value == null) { ps.setNull(rank, Types.VARBINARY); break; } ps.setBytes(rank, (byte[]) value.value); break; case Types.DATE: if (value.value == null) { ps.setNull(rank, Types.DATE); break; } ps.setDate(rank, (Date) value.value); break; case Types.TIMESTAMP: if (value.value == null) { ps.setNull(rank, Types.TIMESTAMP); break; } ps.setTimestamp(rank, (Timestamp) value.value); break; case Types.CLOB: if (value.value == null) { ps.setNull(rank, Types.CLOB); break; } ps.setClob(rank, (Reader) value.value); break; case Types.BLOB: if (value.value == null) { ps.setNull(rank, Types.BLOB); break; } ps.setBlob(rank, (InputStream) value.value); break; default: throw new WaarpDatabaseSqlException("Type not supported: " + value.type + " at " + rank); } } catch (ClassCastException e) { throw new WaarpDatabaseSqlException("Setting values casting error: " + value.type + " at " + rank, e); } catch (SQLException e) { DbSession.error(e); throw new WaarpDatabaseSqlException("Setting values in error: " + value.type + " at " + rank, e); } }