List of usage examples for java.sql ResultSet getBlob
Blob getBlob(String columnLabel) throws SQLException;
ResultSet
object as a Blob
object in the Java programming language. From source file:org.trafodion.rest.util.JdbcT2Util.java
private synchronized JSONArray convertResultSetToJSON(java.sql.ResultSet rs) throws Exception { if (LOG.isDebugEnabled()) LOG.debug("Begin convertResultSetToJSON"); JSONArray json = new JSONArray(); try {// www .j a v a2 s . c om java.sql.ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { int numColumns = rsmd.getColumnCount(); JSONObject obj = new JSONObject(); for (int i = 1; i < numColumns + 1; i++) { String column_name = rsmd.getColumnName(i); if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) { obj.put(column_name, rs.getArray(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) { obj.put(column_name, rs.getLong(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) { obj.put(column_name, rs.getBoolean(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) { obj.put(column_name, rs.getBlob(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) { obj.put(column_name, rs.getDouble(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) { obj.put(column_name, rs.getFloat(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) { obj.put(column_name, rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) { obj.put(column_name, rs.getNString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR || rsmd.getColumnType(i) == java.sql.Types.VARCHAR) { //prevent obj.put from removing null key value from JSONObject String s = rs.getString(column_name); if (s == null) obj.put(column_name, new String("")); else obj.put(column_name, rs.getString(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) { obj.put(column_name, rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) { obj.put(column_name, rs.getInt(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) { obj.put(column_name, rs.getDate(column_name)); } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) { obj.put(column_name, rs.getTimestamp(column_name)); } else { obj.put(column_name, rs.getObject(column_name)); } } //end foreach json.put(obj); } //end while } catch (SQLException e) { e.printStackTrace(); if (LOG.isDebugEnabled()) LOG.error(e.getMessage()); throw e; } catch (Exception e) { e.printStackTrace(); if (LOG.isDebugEnabled()) LOG.error(e.getMessage()); throw e; } if (LOG.isDebugEnabled()) LOG.debug("End convertResultSetToJSON"); return json; }
From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java
@Override public NodeDetail getRemovedNodeData(String nodeId, String groupId, String removedMemberId) throws ClusterCoordinationException { Connection connection = null; PreparedStatement preparedStatement = null; PreparedStatement clearMembershipEvents = null; ResultSet resultSet = null; NodeDetail nodeDetail = null;//from w w w.j av a 2 s . c om try { connection = getConnection(); preparedStatement = connection.prepareStatement(RDBMSConstants.PS_SELECT_REMOVED_MEMBER_DETAILS); preparedStatement.setString(1, nodeId); preparedStatement.setString(2, removedMemberId); preparedStatement.setString(3, groupId); resultSet = preparedStatement.executeQuery(); Map<String, Object> propertiesMap = null; if (resultSet.next()) { Blob blob = resultSet.getBlob(2); if (blob != null) { int blobLength = (int) blob.length(); byte[] bytes = blob.getBytes(1, blobLength); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); Object blobObject = ois.readObject(); if (blobObject instanceof Map) { propertiesMap = (Map) blobObject; } } nodeDetail = new NodeDetail(removedMemberId, groupId, false, 0, false, propertiesMap); } clearMembershipEvents = connection .prepareStatement(RDBMSConstants.PS_DELETE_REMOVED_MEMBER_DETAIL_FOR_NODE); clearMembershipEvents.setString(1, nodeId); clearMembershipEvents.setString(2, removedMemberId); clearMembershipEvents.setString(3, groupId); clearMembershipEvents.executeUpdate(); connection.commit(); } catch (SQLException e) { String errMsg = RDBMSConstants.TASK_GET_ALL_QUEUES; throw new ClusterCoordinationException("Error occurred while " + errMsg, e); } catch (ClassNotFoundException e) { throw new ClusterCoordinationException("Error retrieving the removed node data. ", e); } catch (IOException e) { throw new ClusterCoordinationException("Error retrieving the removed node data. ", e); } finally { close(resultSet, RDBMSConstants.TASK_GET_ALL_QUEUES); close(preparedStatement, RDBMSConstants.TASK_GET_ALL_QUEUES); close(clearMembershipEvents, RDBMSConstants.TASK_GET_ALL_QUEUES); close(connection, RDBMSConstants.TASK_GET_ALL_QUEUES); } return nodeDetail; }
From source file:org.apache.gobblin.source.jdbc.JdbcExtractor.java
private String parseColumnAsString(final ResultSet resultset, final ResultSetMetaData resultsetMetadata, int i) throws SQLException { if (isBlob(resultsetMetadata.getColumnType(i))) { return readBlobAsString(resultset.getBlob(i)); }/*from w w w. ja v a 2 s . co m*/ if (isClob(resultsetMetadata.getColumnType(i))) { return readClobAsString(resultset.getClob(i)); } if ((resultsetMetadata.getColumnType(i) == Types.BIT || resultsetMetadata.getColumnType(i) == Types.BOOLEAN) && convertBitToBoolean()) { return Boolean.toString(resultset.getBoolean(i)); } return resultset.getString(i); }
From source file:org.apache.jackrabbit.core.persistence.pool.BundleDbPersistenceManager.java
/** * Reads and parses a bundle from the BLOB in the given column of the * current row of the given result set. This is a helper method to * circumvent issues JCR-1039 and JCR-1474. * * @param id bundle identifier// w ww. j a va 2 s. com * @param rs result set * @param column BLOB column * @return parsed bundle * @throws SQLException if the bundle can not be read or parsed */ private NodePropBundle readBundle(NodeId id, ResultSet rs, int column) throws SQLException { try { InputStream in; if (rs.getMetaData().getColumnType(column) == Types.BLOB) { in = rs.getBlob(column).getBinaryStream(); } else { in = rs.getBinaryStream(column); } try { return binding.readBundle(in, id); } finally { in.close(); } } catch (IOException e) { SQLException exception = new SQLException("Failed to parse bundle " + id); exception.initCause(e); throw exception; } }
From source file:ubic.gemma.core.externalDb.GoldenPathSequenceAnalysis.java
/** * Uses a query that can retrieve BlatResults from GoldenPath. The query must have the appropriate form. * * @param query query/*from w ww . j a va2s . c om*/ * @param params params * @return blat results */ private Collection<BlatResult> findLocationsByQuery(final String query, final Object[] params) { return this.getJdbcTemplate().query(query, params, new ResultSetExtractor<Collection<BlatResult>>() { @Override public Collection<BlatResult> extractData(ResultSet rs) throws SQLException, DataAccessException { Collection<BlatResult> r = new HashSet<>(); while (rs.next()) { BlatResult blatResult = BlatResult.Factory.newInstance(); Chromosome c = new Chromosome(SequenceManipulation.deBlatFormatChromosomeName(rs.getString(1)), GoldenPathSequenceAnalysis.this.getTaxon()); blatResult.setTargetChromosome(c); Blob blockSizes = rs.getBlob(2); Blob targetStarts = rs.getBlob(3); Blob queryStarts = rs.getBlob(4); blatResult.setBlockSizes(SQLUtils.blobToString(blockSizes)); blatResult.setTargetStarts(SQLUtils.blobToString(targetStarts)); blatResult.setQueryStarts(SQLUtils.blobToString(queryStarts)); blatResult.setStrand(rs.getString(5)); // need the query size to compute scores. blatResult.setQuerySequence(BioSequence.Factory.newInstance()); blatResult.getQuerySequence().setLength(rs.getLong(6)); blatResult.getQuerySequence().setName((String) params[0]); blatResult.setMatches(rs.getInt(7)); blatResult.setMismatches(rs.getInt(8)); blatResult.setQueryGapCount(rs.getInt(9)); blatResult.setTargetGapCount(rs.getInt(10)); blatResult.setQueryStart(rs.getInt(11)); blatResult.setQueryEnd(rs.getInt(12)); blatResult.setTargetStart(rs.getLong(13)); blatResult.setTargetEnd(rs.getLong(14)); blatResult.setRepMatches(rs.getInt(15)); r.add(blatResult); } return r; } }); }
From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java
@Override public NodeDetail getNodeData(String nodeId, String groupId) throws ClusterCoordinationException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; String coordinatorNodeId = getCoordinatorNodeId(groupId); NodeDetail nodeDetail = null;//from w w w . j a v a 2s . c o m try { connection = getConnection(); preparedStatement = connection.prepareStatement(RDBMSConstants.PS_GET_NODE_DATA); preparedStatement.setString(1, groupId); preparedStatement.setString(2, nodeId); resultSet = preparedStatement.executeQuery(); Map<String, Object> propertiesMap = null; if (resultSet.next()) { boolean isCoordinatorNode = coordinatorNodeId.equals(nodeId); if (resultSet.getBlob(3) != null) { int blobLength = (int) resultSet.getBlob(3).length(); byte[] bytes = resultSet.getBlob(3).getBytes(0L, blobLength); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); Object blobObject = ois.readObject(); if (blobObject instanceof Map) { propertiesMap = (Map) blobObject; } } long lastHeartbeat = resultSet.getLong(4); boolean isNewNode = convertIntToBoolean(resultSet.getInt(5)); nodeDetail = new NodeDetail(nodeId, groupId, isCoordinatorNode, lastHeartbeat, isNewNode, propertiesMap); } } catch (SQLException e) { String errMsg = RDBMSConstants.TASK_GET_ALL_QUEUES; throw new ClusterCoordinationException("Error occurred while " + errMsg, e); } catch (IOException e) { throw new ClusterCoordinationException("Error retrieving the node data", e); } catch (ClassNotFoundException e) { throw new ClusterCoordinationException("Error retrieving the node data", e); } finally { close(resultSet, RDBMSConstants.TASK_GET_ALL_QUEUES); close(preparedStatement, RDBMSConstants.TASK_GET_ALL_QUEUES); close(connection, RDBMSConstants.TASK_GET_ALL_QUEUES); } return nodeDetail; }
From source file:com.wabacus.system.component.application.report.configbean.editablereport.AbsEditSqlActionBean.java
public void updateData(ReportRequest rrequest, ReportBean rbean, Map<String, String> mRowData, Map<String, String> mParamValues) throws SQLException { AbsDatabaseType dbtype = rrequest.getDbType(this.ownerGroupBean.getDatasource()); Connection conn = rrequest.getConnection(this.ownerGroupBean.getDatasource()); Oracle oracleType = null;/* w w w .j ava2s .c o m*/ PreparedStatement pstmt = null; try { if (Config.show_sql) log.info("Execute sql:" + sql); pstmt = conn.prepareStatement(sql); if (sql.trim().toLowerCase().startsWith("select ") && (dbtype instanceof Oracle)) { oracleType = (Oracle) dbtype; if (lstParamBeans != null && lstParamBeans.size() > 0) { int colidx = 1; for (EditableReportParamBean paramBean : lstParamBeans) { if ((paramBean.getDataTypeObj() instanceof ClobType) || (paramBean.getDataTypeObj() instanceof BlobType)) continue; paramBean.getDataTypeObj().setPreparedStatementValue(colidx++, getParamValue(mRowData, mParamValues, rbean, rrequest, paramBean), pstmt, dbtype); } } ResultSet rs = pstmt.executeQuery(); while (rs.next()) { if (lstParamBeans != null && lstParamBeans.size() > 0) { int colidx = 1; for (EditableReportParamBean paramBean : lstParamBeans) { if (!(paramBean.getDataTypeObj() instanceof ClobType) && !(paramBean.getDataTypeObj() instanceof BlobType)) continue; String paramvalue = getParamValue(mRowData, mParamValues, rbean, rrequest, paramBean); if (paramBean.getDataTypeObj() instanceof ClobType) { oracleType.setClobValueInSelectMode(paramvalue, (oracle.sql.CLOB) rs.getClob(colidx++)); } else { oracleType.setBlobValueInSelectMode( paramBean.getDataTypeObj().label2value(paramvalue), (oracle.sql.BLOB) rs.getBlob(colidx++)); } } } } rs.close(); } else { if (lstParamBeans != null && lstParamBeans.size() > 0) { int idx = 1; for (EditableReportParamBean paramBean : lstParamBeans) { paramBean.getDataTypeObj().setPreparedStatementValue(idx++, getParamValue(mRowData, mParamValues, rbean, rrequest, paramBean), pstmt, dbtype); } } int rtnVal = pstmt.executeUpdate(); storeReturnValue(rrequest, mParamValues, String.valueOf(rtnVal)); } } finally { WabacusAssistant.getInstance().release(null, pstmt); } }
From source file:org.snaker.engine.access.jdbc.JdbcHelper.java
/** * ?ResultSet?index?requiredType?/*from www .j a v a2s. c o m*/ * @param rs * @param index * @param requiredType * @return * @throws SQLException */ public static Object getResultSetValue(ResultSet rs, int index, Class<?> requiredType) throws SQLException { if (requiredType == null) { return getResultSetValue(rs, index); } Object value = null; boolean wasNullCheck = false; if (String.class.equals(requiredType)) { value = rs.getString(index); } else if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) { value = rs.getBoolean(index); wasNullCheck = true; } else if (byte.class.equals(requiredType) || Byte.class.equals(requiredType)) { value = rs.getByte(index); wasNullCheck = true; } else if (short.class.equals(requiredType) || Short.class.equals(requiredType)) { value = rs.getShort(index); wasNullCheck = true; } else if (int.class.equals(requiredType) || Integer.class.equals(requiredType)) { value = rs.getInt(index); wasNullCheck = true; } else if (long.class.equals(requiredType) || Long.class.equals(requiredType)) { value = rs.getLong(index); wasNullCheck = true; } else if (float.class.equals(requiredType) || Float.class.equals(requiredType)) { value = rs.getFloat(index); wasNullCheck = true; } else if (double.class.equals(requiredType) || Double.class.equals(requiredType) || Number.class.equals(requiredType)) { value = rs.getDouble(index); wasNullCheck = true; } else if (byte[].class.equals(requiredType)) { value = rs.getBytes(index); } else if (java.sql.Date.class.equals(requiredType)) { value = rs.getDate(index); } else if (java.sql.Time.class.equals(requiredType)) { value = rs.getTime(index); } else if (java.sql.Timestamp.class.equals(requiredType) || java.util.Date.class.equals(requiredType)) { value = rs.getTimestamp(index); } else if (BigDecimal.class.equals(requiredType)) { value = rs.getBigDecimal(index); } else if (Blob.class.equals(requiredType)) { value = rs.getBlob(index); } else if (Clob.class.equals(requiredType)) { value = rs.getClob(index); } else { value = getResultSetValue(rs, index); } if (wasNullCheck && value != null && rs.wasNull()) { value = null; } return value; }
From source file:com.wabacus.system.dataset.update.action.rationaldb.AbsRationalDBUpdateAction.java
private int updateDataByPreparedstatement(ReportRequest rrequest, Map<String, String> mRowData, Map<String, String> mParamValues, PreparedStatement pstmt, String sql) throws SQLException { AbsDatabaseType dbtype = rrequest.getDbType(this.datasource); Oracle oracleType = null;/* ww w . j a v a 2s . co m*/ ReportBean rbean = this.ownerUpdateBean.getOwner().getReportBean(); int rtnVal = 1; if (sql.trim().toLowerCase().startsWith("select ") && (dbtype instanceof Oracle)) {//?SQL? oracleType = (Oracle) dbtype; if (lstParamBeans != null && lstParamBeans.size() > 0) { int colidx = 1; for (EditableReportParamBean paramBean : lstParamBeans) { if ((paramBean.getDataTypeObj() instanceof ClobType) || (paramBean.getDataTypeObj() instanceof BlobType)) continue; paramBean.getDataTypeObj() .setPreparedStatementValue( colidx++, paramBean.getRuntimeParamValue(rrequest, rbean, mRowData, mParamValues, this.datasource, ownerUpdateBean.isAutoReportdata()), pstmt, dbtype); } } ResultSet rs = pstmt.executeQuery(); while (rs.next()) { if (lstParamBeans != null && lstParamBeans.size() > 0) { int colidx = 1; for (EditableReportParamBean paramBean : lstParamBeans) { if (!(paramBean.getDataTypeObj() instanceof ClobType) && !(paramBean.getDataTypeObj() instanceof BlobType)) continue; String paramvalue = paramBean.getRuntimeParamValue(rrequest, rbean, mRowData, mParamValues, this.datasource, ownerUpdateBean.isAutoReportdata()); if (paramBean.getDataTypeObj() instanceof ClobType) { oracleType.setClobValueInSelectMode(paramvalue, (oracle.sql.CLOB) rs.getClob(colidx++)); } else { oracleType.setBlobValueInSelectMode(paramBean.getDataTypeObj().label2value(paramvalue), (oracle.sql.BLOB) rs.getBlob(colidx++)); } } } } rs.close(); } else { if (lstParamBeans != null && lstParamBeans.size() > 0) { int idx = 1; for (EditableReportParamBean paramBean : lstParamBeans) { paramBean.getDataTypeObj() .setPreparedStatementValue(idx++, paramBean.getRuntimeParamValue(rrequest, rbean, mRowData, mParamValues, this.datasource, ownerUpdateBean.isAutoReportdata()), pstmt, dbtype); } } rtnVal = pstmt.executeUpdate(); } return rtnVal; }
From source file:org.apache.nifi.processors.standard.util.JdbcCommon.java
public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, String recordName, ResultSetRowCallback callback, final int maxRows, boolean convertNames) throws SQLException, IOException { final Schema schema = createSchema(rs, recordName, convertNames); final GenericRecord rec = new GenericData.Record(schema); final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) { dataFileWriter.create(schema, outStream); final ResultSetMetaData meta = rs.getMetaData(); final int nrOfColumns = meta.getColumnCount(); long nrOfRows = 0; while (rs.next()) { if (callback != null) { callback.processRow(rs); }//ww w . j ava2 s.c o m for (int i = 1; i <= nrOfColumns; i++) { final int javaSqlType = meta.getColumnType(i); // Need to handle CLOB and BLOB before getObject() is called, due to ResultSet's maximum portability statement if (javaSqlType == CLOB) { Clob clob = rs.getClob(i); if (clob != null) { long numChars = clob.length(); char[] buffer = new char[(int) numChars]; InputStream is = clob.getAsciiStream(); int index = 0; int c = is.read(); while (c > 0) { buffer[index++] = (char) c; c = is.read(); } rec.put(i - 1, new String(buffer)); clob.free(); } else { rec.put(i - 1, null); } continue; } if (javaSqlType == BLOB) { Blob blob = rs.getBlob(i); if (blob != null) { long numChars = blob.length(); byte[] buffer = new byte[(int) numChars]; InputStream is = blob.getBinaryStream(); int index = 0; int c = is.read(); while (c > 0) { buffer[index++] = (byte) c; c = is.read(); } ByteBuffer bb = ByteBuffer.wrap(buffer); rec.put(i - 1, bb); blob.free(); } else { rec.put(i - 1, null); } continue; } final Object value = rs.getObject(i); if (value == null) { rec.put(i - 1, null); } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY || javaSqlType == ARRAY) { // bytes requires little bit different handling byte[] bytes = rs.getBytes(i); ByteBuffer bb = ByteBuffer.wrap(bytes); rec.put(i - 1, bb); } else if (value instanceof Byte) { // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT // But value is returned by JDBC as java.lang.Byte // (at least H2 JDBC works this way) // direct put to avro record results: // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte rec.put(i - 1, ((Byte) value).intValue()); } else if (value instanceof Short) { //MS SQL returns TINYINT as a Java Short, which Avro doesn't understand. rec.put(i - 1, ((Short) value).intValue()); } else if (value instanceof BigDecimal) { // Avro can't handle BigDecimal as a number - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38" rec.put(i - 1, value.toString()); } else if (value instanceof BigInteger) { // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that. // It the SQL type is BIGINT and the precision is between 0 and 19 (inclusive); if so, the BigInteger is likely a // long (and the schema says it will be), so try to get its value as a long. // Otherwise, Avro can't handle BigInteger as a number - it will throw an AvroRuntimeException // such as: "Unknown datum type: java.math.BigInteger: 38". In this case the schema is expecting a string. if (javaSqlType == BIGINT) { int precision = meta.getPrecision(i); if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) { rec.put(i - 1, value.toString()); } else { try { rec.put(i - 1, ((BigInteger) value).longValueExact()); } catch (ArithmeticException ae) { // Since the value won't fit in a long, convert it to a string rec.put(i - 1, value.toString()); } } } else { rec.put(i - 1, value.toString()); } } else if (value instanceof Number || value instanceof Boolean) { if (javaSqlType == BIGINT) { int precision = meta.getPrecision(i); if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) { rec.put(i - 1, value.toString()); } else { rec.put(i - 1, value); } } else { rec.put(i - 1, value); } } else { // The different types that we support are numbers (int, long, double, float), // as well as boolean values and Strings. Since Avro doesn't provide // timestamp types, we want to convert those to Strings. So we will cast anything other // than numbers or booleans to strings by using the toString() method. rec.put(i - 1, value.toString()); } } dataFileWriter.append(rec); nrOfRows += 1; if (maxRows > 0 && nrOfRows == maxRows) break; } return nrOfRows; } }