List of usage examples for java.sql PreparedStatement setCharacterStream
void setCharacterStream(int parameterIndex, java.io.Reader reader, long length) throws SQLException;
Reader
object, which is the given number of characters long. From source file:org.castor.jdo.engine.SQLTypeInfos.java
/** * Set given value on given PreparedStatement at given index with given SQL type. * /*w w w . ja v a2s . co m*/ * @param stmt The PreparedStatement to set value on. * @param index The index of the value in the PreparedStatement. * @param value The value to set. * @param sqlType The SQL type of the value. */ public static void setValue(final PreparedStatement stmt, final int index, final Object value, final int sqlType) { try { if (value == null) { stmt.setNull(index, sqlType); } else { // Special processing for BLOB and CLOB types, because they are mapped // by Castor to java.io.InputStream and java.io.Reader, respectively, // while JDBC driver expects java.sql.Blob and java.sql.Clob. switch (sqlType) { case Types.FLOAT: case Types.DOUBLE: stmt.setDouble(index, ((Double) value).doubleValue()); break; case Types.REAL: stmt.setFloat(index, ((Float) value).floatValue()); break; case Types.TIME: final Time time = value instanceof java.util.Date ? new Time(((java.util.Date) value).getTime()) : null; stmt.setTime(index, time != null ? time : (Time) value, getCalendar()); break; case Types.DATE: final Date date = value instanceof java.util.Date ? new Date(((java.util.Date) value).getTime()) : null; stmt.setDate(index, date != null ? date : (Date) value); break; case Types.TIMESTAMP: final Timestamp timestamp = value instanceof java.util.Date ? new Timestamp(((java.util.Date) value).getTime()) : null; stmt.setTimestamp(index, timestamp != null ? timestamp : (Timestamp) value, getCalendar()); break; case Types.BLOB: try { InputStream stream; if (value instanceof byte[]) { stream = new ByteArrayInputStream((byte[]) value); } else { stream = (InputStream) value; } stmt.setBinaryStream(index, stream, stream.available()); } catch (IOException ex) { throw new SQLException(ex.toString()); } break; case Types.CLOB: if (value instanceof String) { stmt.setCharacterStream(index, new StringReader((String) value), Math.min(((String) value).length(), Integer.MAX_VALUE)); } else { stmt.setCharacterStream(index, ((Clob) value).getCharacterStream(), (int) Math.min(((Clob) value).length(), Integer.MAX_VALUE)); } break; default: stmt.setObject(index, value, sqlType); break; } } } catch (SQLException ex) { LOG.error("Unexpected SQL exception: ", ex); } }
From source file:org.geowebcache.storage.jdbc.jobstore.JDBCJobWrapper.java
public void putJobLog(JobLogObject stObj) throws SQLException, StorageException { // Not really a fan of tacking log_ onto the front of every field, but it ensures // common keywords like log, level, time, summary, text won't clash with database // keywords, causing unnecessary pain. String query = "MERGE INTO " + "JOB_LOGS(job_log_id, job_id, log_level, log_time, log_summary, log_text) " + "KEY(job_log_id) " + "VALUES(?,?,?,?,?,?)"; final Connection conn = getConnection(); try {//from www.j ava 2 s . c o m Long insertId; PreparedStatement prep = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); try { if (stObj.getJobLogId() == -1) { prep.setNull(1, java.sql.Types.BIGINT); } else { prep.setLong(1, stObj.getJobLogId()); } prep.setLong(2, stObj.getJobId()); prep.setString(3, stObj.getLogLevel().name()); prep.setTimestamp(4, stObj.getLogTime()); prep.setString(5, stObj.getLogSummary()); Reader reader = (Reader) new BufferedReader(new StringReader(stObj.getLogText())); prep.setCharacterStream(6, reader, stObj.getLogText().length()); insertId = wrappedInsert(prep); } finally { close(prep); } if (insertId == null) { log.error("Did not receive an id for " + query); } else { if (stObj.getJobLogId() == -1) { // only use the inserted id if we were doing an insert. // what insertid will be if we weren't doing an insert is not defined. stObj.setJobLogId(insertId.longValue()); } } } finally { conn.close(); } }
From source file:org.jbpm.db.hibernate.SybaseTextType.java
public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException { String str = (String) value; st.setCharacterStream(index, new StringReader(str), str.length()); }
From source file:org.jbpm.db.hibernate.SybaseTextType.java
public void setNull(PreparedStatement st, int index) throws HibernateException, SQLException { // JBPM-1818: workaround for SQL state JZ0SL: "Unsupported SQL type" with jConnect st.setCharacterStream(index, null, 0); }
From source file:org.kawanfw.sql.servlet.sql.ServerCallableStatementParameters.java
/** * Sets the character stream using the underlying Clob file uploaded by the * client side//from www . j a v a 2 s. c o m * * @param preparedStatement * The Prepared Statement to execute * @param parameterIndex * the parameter index * @param paramValue * the parameter value (the file name) * @throws SQLException */ private void setCharacterStream(PreparedStatement preparedStatement, int parameterIndex, String paramValue) throws SQLException, IOException { // Extract the Clob file from the parameter File clobFile = getFileFromParameter(paramValue); Reader reader = null; long theLength = -1; if (callableStatementHolder.isHtmlEncodingOn()) { File clobFileHtmlDecoded = new File(clobFile + HTML_DECODED); blobsOrClobs.add(clobFileHtmlDecoded); BufferedReader br = null; Writer writer = null; try { br = new BufferedReader(new FileReader(clobFile)); writer = new BufferedWriter(new FileWriter(clobFileHtmlDecoded)); String line = null; while ((line = br.readLine()) != null) { line = HtmlConverter.fromHtml(line); writer.write(line + CR_LF); } } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(writer); if (!KeepTempFilePolicyParms.KEEP_TEMP_FILE && !DEBUG) { clobFile.delete(); } } reader = new BufferedReader(new FileReader(clobFileHtmlDecoded)); theLength = clobFileHtmlDecoded.length(); } else { blobsOrClobs.add(clobFile); reader = new BufferedReader(new FileReader(clobFile)); theLength = clobFile.length(); } // We cast theLength, because the long version may not be implemented by // the driver preparedStatement.setCharacterStream(parameterIndex, reader, (int) theLength); this.readerList.add(reader); }
From source file:org.kawanfw.sql.servlet.sql.ServerPreparedStatementParameters.java
/** * Sets the character stream using the underlying Clob file uploaded by the * client side/*from ww w .jav a2 s .c om*/ * * @param preparedStatement * The Prepared Statement to execute * @param parameterIndex * the parameter index * @param paramValue * the parameter value (the file name) * @throws SQLException */ private void setCharacterStream(PreparedStatement preparedStatement, int parameterIndex, String paramValue) throws SQLException, IOException { // Extract the Clob file from the parameter File clobFile = getFileFromParameter(paramValue); Reader reader = null; long theLength = -1; if (statementHolder.isHtmlEncodingOn()) { File clobFileHtmlDecoded = new File(clobFile + HTML_DECODED); blobsOrClobs.add(clobFileHtmlDecoded); BufferedReader br = null; Writer writer = null; try { br = new BufferedReader(new FileReader(clobFile)); writer = new BufferedWriter(new FileWriter(clobFileHtmlDecoded)); String line = null; while ((line = br.readLine()) != null) { line = HtmlConverter.fromHtml(line); writer.write(line + CR_LF); } } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(writer); if (!KeepTempFilePolicyParms.KEEP_TEMP_FILE && !DEBUG) { clobFile.delete(); } } reader = new BufferedReader(new FileReader(clobFileHtmlDecoded)); theLength = clobFileHtmlDecoded.length(); } else { blobsOrClobs.add(clobFile); reader = new BufferedReader(new FileReader(clobFile)); theLength = clobFile.length(); } // We cast theLength, because the long version may not be implemented by // the driver preparedStatement.setCharacterStream(parameterIndex, reader, (int) theLength); this.readerList.add(reader); }
From source file:org.kawanfw.test.api.client.InsertAndUpdateClobTest.java
public void updateclob(Connection connection, File file) throws Exception { PreparedStatement prepStatement = null; String sql = "update documentation set " + " item_doc = ? " + " where item_id >= ?"; prepStatement = connection.prepareStatement(sql); Reader reader = new BufferedReader(new FileReader(file)); int i = 1;/*from ww w.ja va2 s.co m*/ prepStatement.setCharacterStream(i++, reader, (int) file.length()); prepStatement.setInt(i++, 1); prepStatement.executeUpdate(); prepStatement.close(); // important to delete temp files }
From source file:org.kawanfw.test.api.client.InsertAndUpdateClobTest.java
/** * Insert a CLOB//from ww w.ja va2 s . c o m * * @throws Exception * it any Exception occurs */ public void insertLoopPrepStatement(Connection connection, int numberToInsert, File file) throws Exception { // We can now use our Remote JDBC Connection as a regular Connection! connection.setAutoCommit(false); // We will do all our remote insert in a SQL Transaction try { String sql = "insert into documentation values ( ?, ? )"; // Create a new Prepared Statement PreparedStatement prepStatement = null; MessageDisplayer.display(""); MessageDisplayer.display("Inserting " + numberToInsert + " documentation..."); for (int customerId = 1; customerId < numberToInsert + 1; customerId++) { int i = 1; // We will insert a Blob (the image of the product). // The transfer will be done in streaming both on the client // and on the Servlet Server: we can upload/download very big // files. Reader in = new BufferedReader(new FileReader(file)); prepStatement = connection.prepareStatement(sql); prepStatement.setInt(i++, customerId); prepStatement.setCharacterStream(i++, in, (int) file.length()); prepStatement.executeUpdate(); prepStatement.close(); } // We do either everything in a single transaction or nothing connection.commit(); // Commit is propagated on Server MessageDisplayer.display("Remote Commit Done on AceQL Server!"); } catch (Exception e) { connection.rollback(); throw e; } finally { connection.setAutoCommit(true); } }
From source file:org.pentaho.platform.repository.hibernate.usertypes.LongStringUserType.java
public void nullSafeSet(final PreparedStatement st, final Object value, final int index) throws HibernateException, SQLException { if (LongStringUserType.debug) { LongStringUserType.log.debug(Messages.getInstance().getString("LONGSTRTYPE.DEBUG_NULL_SAFE_SET")); //$NON-NLS-1$ }//from ww w. j a va 2 s. co m if (value != null) { StringReader rdr = new StringReader(value.toString()); int sLen = ((StringBuffer) value).length(); st.setCharacterStream(index, rdr, sLen); } else { st.setNull(index, LongStringUserType.SQLTYPE[0]); } }
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 a va 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 \"{} 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; } }