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.executequery.gui.resultset.ResultSetTableModel.java
public void createTable(ResultSet resultSet) { if (!isOpenAndValid(resultSet)) { clearData();/*from w w w. j av a 2s. c o m*/ return; } try { resetMetaData(); ResultSetMetaData rsmd = resultSet.getMetaData(); columnHeaders.clear(); visibleColumnHeaders.clear(); tableData.clear(); int zeroBaseIndex = 0; int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { zeroBaseIndex = i - 1; columnHeaders.add(new ResultSetColumnHeader(zeroBaseIndex, rsmd.getColumnLabel(i), rsmd.getColumnName(i), rsmd.getColumnType(i), rsmd.getColumnTypeName(i))); } int recordCount = 0; interrupted = false; if (holdMetaData) { setMetaDataVectors(rsmd); } List<RecordDataItem> rowData; long time = System.currentTimeMillis(); while (resultSet.next()) { if (interrupted || Thread.interrupted()) { throw new InterruptedException(); } recordCount++; rowData = new ArrayList<RecordDataItem>(count); for (int i = 1; i <= count; i++) { zeroBaseIndex = i - 1; ResultSetColumnHeader header = columnHeaders.get(zeroBaseIndex); RecordDataItem value = recordDataItemFactory.create(header); try { int dataType = header.getDataType(); switch (dataType) { // some drivers (informix for example) // was noticed to return the hashcode from // getObject for -1 data types (eg. longvarchar). // force string for these - others stick with // getObject() for default value formatting case Types.CHAR: case Types.VARCHAR: value.setValue(resultSet.getString(i)); break; case Types.DATE: value.setValue(resultSet.getDate(i)); break; case Types.TIME: value.setValue(resultSet.getTime(i)); break; case Types.TIMESTAMP: value.setValue(resultSet.getTimestamp(i)); break; case Types.LONGVARCHAR: case Types.CLOB: value.setValue(resultSet.getClob(i)); break; case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: value.setValue(resultSet.getBytes(i)); break; case Types.BLOB: value.setValue(resultSet.getBlob(i)); break; case Types.BIT: case Types.TINYINT: case Types.SMALLINT: case Types.INTEGER: case Types.BIGINT: case Types.FLOAT: case Types.REAL: case Types.DOUBLE: case Types.NUMERIC: case Types.DECIMAL: case Types.NULL: case Types.OTHER: case Types.JAVA_OBJECT: case Types.DISTINCT: case Types.STRUCT: case Types.ARRAY: case Types.REF: case Types.DATALINK: case Types.BOOLEAN: case Types.ROWID: case Types.NCHAR: case Types.NVARCHAR: case Types.LONGNVARCHAR: case Types.NCLOB: case Types.SQLXML: // use getObject for all other known types value.setValue(resultSet.getObject(i)); break; default: // otherwise try as string asStringOrObject(value, resultSet, i); break; } } catch (Exception e) { try { // ... and on dump, resort to string value.setValue(resultSet.getString(i)); } catch (SQLException sqlException) { // catch-all SQLException - yes, this is hideous // noticed with invalid date formatted values in mysql value.setValue("<Error - " + sqlException.getMessage() + ">"); } } if (resultSet.wasNull()) { value.setNull(); } rowData.add(value); } tableData.add(rowData); if (recordCount == maxRecords) { break; } } if (Log.isTraceEnabled()) { Log.trace("Finished populating table model - " + recordCount + " rows - [ " + MiscUtils.formatDuration(System.currentTimeMillis() - time) + "]"); } fireTableStructureChanged(); } catch (SQLException e) { System.err.println("SQL error populating table model at: " + e.getMessage()); Log.debug("Table model error - " + e.getMessage(), e); } catch (Exception e) { if (e instanceof InterruptedException) { Log.debug("ResultSet generation interrupted.", e); } else { String message = e.getMessage(); if (StringUtils.isBlank(message)) { System.err.println("Exception populating table model."); } else { System.err.println("Exception populating table model at: " + message); } Log.debug("Table model error - ", e); } } finally { if (resultSet != null) { try { resultSet.close(); Statement statement = resultSet.getStatement(); if (statement != null) { statement.close(); } } catch (SQLException e) { } } } }
From source file:ubic.gemma.externalDb.GoldenPathSequenceAnalysis.java
/** * Generic method to retrieve Genes from the GoldenPath database. The query given must have the appropriate form. * //ww w.j a va 2 s. c om * @param starti * @param endi * @param chromosome * @param query * @return List of GeneProducts. * @throws SQLException */ private Collection<GeneProduct> findGenesByQuery(Long starti, Long endi, final String chromosome, String strand, String query) { // Cases: // 1. gene is contained within the region: txStart > start & txEnd < end; // 2. region is contained within the gene: txStart < start & txEnd > end; // 3. region overlaps start of gene: txStart > start & txStart < end. // 4. region overlaps end of gene: txEnd > start & txEnd < end // Object[] params; if (strand != null) { params = new Object[] { starti, endi, starti, endi, starti, endi, starti, endi, chromosome, strand }; } else { params = new Object[] { starti, endi, starti, endi, starti, endi, starti, endi, chromosome }; } return this.getJdbcTemplate().query(query, params, new ResultSetExtractor<Collection<GeneProduct>>() { @Override public Collection<GeneProduct> extractData(ResultSet rs) throws SQLException, DataAccessException { Collection<GeneProduct> r = new HashSet<GeneProduct>(); while (rs.next()) { GeneProduct product = GeneProduct.Factory.newInstance(); String name = rs.getString(1); /* * This happens for a very few cases in kgXref, where the gene is 'abParts'. We have to skip these. */ if (StringUtils.isBlank(name)) { continue; } /* * The name is our database identifier (either genbank or ensembl) */ DatabaseEntry accession = DatabaseEntry.Factory.newInstance(); accession.setAccession(name); if (name.startsWith("ENST")) { accession.setExternalDatabase(NcbiGeneConverter.getEnsembl()); } else { accession.setExternalDatabase(NcbiGeneConverter.getGenbank()); } // FIXME could be a microRNA. product.getAccessions().add(accession); product.setType(GeneProductType.RNA); Gene gene = Gene.Factory.newInstance(); gene.setOfficialSymbol(rs.getString(2)); gene.setName(gene.getOfficialSymbol()); Taxon taxon = getTaxon(); assert taxon != null; gene.setTaxon(taxon); PhysicalLocation pl = PhysicalLocation.Factory.newInstance(); pl.setNucleotide(rs.getLong(3)); pl.setNucleotideLength(rs.getInt(4) - rs.getInt(3)); pl.setStrand(rs.getString(5)); pl.setBin(SequenceBinUtils.binFromRange((int) rs.getLong(3), rs.getInt(4))); PhysicalLocation genePl = PhysicalLocation.Factory.newInstance(); genePl.setStrand(pl.getStrand()); Chromosome c = Chromosome.Factory.newInstance(); c.setName(SequenceManipulation.deBlatFormatChromosomeName(chromosome)); c.setTaxon(taxon); pl.setChromosome(c); genePl.setChromosome(c); /* * this only contains the chromosome and strand: the nucleotide positions are only valid for the * gene product */ gene.setPhysicalLocation(genePl); product.setName(name); String descriptionFromGP = rs.getString(8); if (StringUtils.isBlank(descriptionFromGP)) { product.setDescription("Imported from GoldenPath"); } else { product.setDescription("Imported from Golden Path: " + descriptionFromGP); } product.setPhysicalLocation(pl); product.setGene(gene); Blob exonStarts = rs.getBlob(6); Blob exonEnds = rs.getBlob(7); product.setExons(getExons(c, exonStarts, exonEnds)); /* * For microRNAs, we don't get exons, so we just use the whole length for now. */ if (product.getExons().size() == 0) { product.getExons().add(pl); } r.add(product); } return r; } }); }
From source file:org.wso2.appcloud.core.dao.ApplicationDAO.java
/** * Method for getting the list of tagged applications per cloud * * @param dbConnection database connection * @param tenantId tenant id/*from www .ja v a 2 s.c o m*/ * @param cloudType cloud type * @return taggedApplicationsList List of all the tagged applications per cloud * @throws AppCloudException */ public List<Application> getTaggedApplicationsList(Connection dbConnection, int tenantId, String cloudType) throws AppCloudException { PreparedStatement preparedStatement = null; List<Application> taggedApplicationsList = new ArrayList<>(); ResultSet resultSet = null; try { preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.GET_ALL_APPLICATIONS_LIST_WITH_TAG); preparedStatement.setInt(1, tenantId); preparedStatement.setString(2, cloudType); resultSet = preparedStatement.executeQuery(); boolean applicationAddedtoList; while (resultSet.next()) { Tag tag; applicationAddedtoList = false; //Iterating the existing tagged application list to check whether the application is already added into the list for (Application application : taggedApplicationsList) { String hashId = resultSet.getString(SQLQueryConstants.HASH_ID); if (application.getHashId().equals(hashId)) { applicationAddedtoList = true; tag = new Tag(); tag.setTagName(resultSet.getString(SQLQueryConstants.TAG_KEY)); tag.setTagValue(resultSet.getString(SQLQueryConstants.TAG_VALUE)); if (application.getVersions() != null && application.getVersions().get(0) != null) { application.getVersions().get(0).getTags().add(tag); } } } //Adding a new application if it is not already in the tagged application list if (!applicationAddedtoList) { Application application = new Application(); application.setApplicationName(resultSet.getString(SQLQueryConstants.APPLICATION_NAME)); application.setApplicationType(resultSet.getString(SQLQueryConstants.APPLICATION_TYPE_NAME)); application.setHashId(resultSet.getString(SQLQueryConstants.HASH_ID)); application.setIcon(resultSet.getBlob(SQLQueryConstants.ICON)); List<Tag> tags = new ArrayList<>(); Version version = new Version(); tag = new Tag(); tag.setTagName(resultSet.getString(SQLQueryConstants.TAG_KEY)); tag.setTagValue(resultSet.getString(SQLQueryConstants.TAG_VALUE)); tags.add(tag); version.setTags(tags); application.setVersions(Collections.singletonList(version)); taggedApplicationsList.add(application); } } } catch (SQLException e) { String msg = "Error while retrieving application list from database in tenant : " + tenantId + " and cloud : " + cloudType; throw new AppCloudException(msg, e); } finally { DBUtil.closeResultSet(resultSet); DBUtil.closePreparedStatement(preparedStatement); } return taggedApplicationsList; }
From source file:com.nway.spring.jdbc.bean.JavassistBeanProcessor.java
private Object processColumn(ResultSet rs, int index, Class<?> propType, String writer, StringBuilder handler) throws SQLException { if (propType.equals(String.class)) { handler.append("bean.").append(writer).append("(").append("$1.getString(").append(index).append("));"); return rs.getString(index); } else if (propType.equals(Integer.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getInt(").append(index).append("));"); return rs.getInt(index); } else if (propType.equals(Integer.class)) { handler.append("bean.").append(writer).append("(").append("integerValue($1.getInt(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Integer.class); } else if (propType.equals(Long.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getLong(").append(index).append("));"); return rs.getLong(index); } else if (propType.equals(Long.class)) { handler.append("bean.").append(writer).append("(").append("longValue($1.getLong(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Long.class); } else if (propType.equals(java.sql.Date.class)) { handler.append("bean.").append(writer).append("(").append("$1.getDate(").append(index).append("));"); return rs.getDate(index); } else if (propType.equals(java.util.Date.class) || propType.equals(Timestamp.class)) { handler.append("bean.").append(writer).append("(").append("$1.getTimestamp(").append(index) .append("));"); return rs.getTimestamp(index); } else if (propType.equals(Double.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getDouble(").append(index).append("));"); return rs.getDouble(index); } else if (propType.equals(Double.class)) { handler.append("bean.").append(writer).append("(").append("doubleValue($1.getDouble(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Double.class); } else if (propType.equals(Float.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getFloat(").append(index).append("));"); return rs.getFloat(index); } else if (propType.equals(Float.class)) { handler.append("bean.").append(writer).append("(").append("floatValue($1.getFloat(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Float.class); } else if (propType.equals(Time.class)) { handler.append("bean.").append(writer).append("(").append("$1.getTime(").append(index).append("));"); return rs.getTime(index); } else if (propType.equals(Boolean.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getBoolean(").append(index).append("));"); return rs.getBoolean(index); } else if (propType.equals(Boolean.class)) { handler.append("bean.").append(writer).append("(").append("booleanValue($1.getBoolean(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Boolean.class); } else if (propType.equals(byte[].class)) { handler.append("bean.").append(writer).append("(").append("$1.getBytes(").append(index).append("));"); return rs.getBytes(index); } else if (BigDecimal.class.equals(propType)) { handler.append("bean.").append(writer).append("(").append("$1.getBigDecimal(").append(index) .append("));"); return rs.getBigDecimal(index); } else if (Blob.class.equals(propType)) { handler.append("bean.").append(writer).append("(").append("$1.getBlob(").append(index).append("));"); return rs.getBlob(index); } else if (Clob.class.equals(propType)) { handler.append("bean.").append(writer).append("(").append("$1.getClob(").append(index).append("));"); return rs.getClob(index); } else if (propType.equals(Short.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getShort(").append(index).append("));"); return rs.getShort(index); } else if (propType.equals(Short.class)) { handler.append("bean.").append(writer).append("(").append("shortValue($1.getShort(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Short.class); } else if (propType.equals(Byte.TYPE)) { handler.append("bean.").append(writer).append("(").append("$1.getByte(").append(index).append("));"); return rs.getByte(index); } else if (propType.equals(Byte.class)) { handler.append("bean.").append(writer).append("(").append("byteValue($1.getByte(").append(index) .append("),$1.wasNull()));"); return JdbcUtils.getResultSetValue(rs, index, Byte.class); } else {//from ww w .j a v a 2 s . co m handler.append("bean.").append(writer).append("(").append("(").append(propType.getName()).append(")") .append("$1.getObject(").append(index).append("));"); return rs.getObject(index); } }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private synchronized LogIndex unpauseLogIndex(String paxosID) { if (isClosed() /* || !isLoggingEnabled() */) return null; log.log(Level.FINER, "{0} trying to unpause logIndex for {1}", new Object[] { this, paxosID }); PreparedStatement pstmt = null; ResultSet rset = null; Connection conn = null;//from w w w.j ava2s . c om LogIndex logIndex = null; String logIndexString = null; try { conn = this.getDefaultConn(); pstmt = this.getPreparedStatement(conn, (USE_CHECKPOINTS_AS_PAUSE_TABLE ? getCTable() : getPTable()), paxosID, "logindex"); rset = pstmt.executeQuery(); while (rset.next()) { Blob logIndexBlob = rset.getBlob(1); if (logIndexBlob == null) continue; logIndexString = (lobToString(logIndexBlob)); logIndex = new LogIndex(new JSONArray(logIndexString)); this.messageLog.restore(logIndex); log.log(Level.FINE, "{0} unpaused logIndex for {1}", new Object[] { this, paxosID }); } } catch (SQLException | JSONException | IOException e) { log.severe(this + " failed to unpause instance " + paxosID + "; logIndex = " + logIndexString); e.printStackTrace(); } finally { cleanup(pstmt, rset); cleanup(conn); } return logIndex; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private String getCheckpointState(String table, String paxosID, String column) { if (isClosed()) return null; String state = null;/* ww w. j a va 2 s . c o m*/ PreparedStatement pstmt = null; ResultSet stateRS = null; Connection conn = null; try { conn = getDefaultConn(); pstmt = getPreparedStatement(conn, table, paxosID, column); stateRS = pstmt.executeQuery(); while (stateRS.next()) { assert (state == null); // single result state = (!getCheckpointBlobOption() || !column.equals("state") ? stateRS.getString(1) : lobToString(stateRS.getBlob(1))); } } catch (IOException e) { log.severe("IOException while getting state " + " : " + e); e.printStackTrace(); } catch (SQLException sqle) { log.severe("SQLException while getting state: " + table + " " + paxosID + " " + column + " : " + sqle); sqle.printStackTrace(); } finally { cleanup(pstmt, stateRS); cleanup(conn); } return state; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
@Override public/* synchronized */HotRestoreInfo unpause(String paxosID) { if (isClosed() /* || !isLoggingEnabled() */) return null; HotRestoreInfo hri = null;/*from w w w. j a va 2 s . com*/ PreparedStatement pstmt = null; ResultSet rset = null; Connection conn = null; String logIndexString = null; try { conn = this.getDefaultConn(); pstmt = this.getPreparedStatement(conn, (USE_CHECKPOINTS_AS_PAUSE_TABLE ? getCTable() : getPTable()), paxosID, "serialized, logindex"); rset = pstmt.executeQuery(); while (rset.next()) { assert (hri == null); // exactly onece String serialized = rset.getString(1); // no clob option if (serialized != null) hri = new HotRestoreInfo(serialized); Blob logIndexBlob = rset.getBlob(2); logIndexString = lobToString(logIndexBlob); if (logIndexBlob != null) { this.messageLog.restore(new LogIndex(new JSONArray(logIndexString))); } } } catch (SQLException | JSONException | IOException e) { log.severe(this + " failed to unpause instance " + paxosID + "; logIndex = " + logIndexString); e.printStackTrace(); } finally { cleanup(pstmt, rset); cleanup(conn); } ; if (hri != null) { log.log(Level.FINEST, "{0} unpaused {1} and about to delete pause state", new Object[] { this, paxosID }); this.deletePaused(paxosID); // unpause will also delete paused state } return hri; }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
private boolean isLogged(String paxosID, int slot, int ballotnum, int coordinator, String msg) { PreparedStatement pstmt = null; ResultSet messagesRS = null; Connection conn = null;//from www .j a va2s. c om String cmd = "select paxos_id, message from " + getMTable() + " where paxos_id='" + paxosID + "' " + " and slot=" + slot + " and ballotnum=" + ballotnum + " and coordinator=" + coordinator + (getLogMessageBlobOption() ? "" : " and message=?"); boolean logged = false; try { conn = this.getDefaultConn(); pstmt = conn.prepareStatement(cmd); if (!getLogMessageBlobOption()) pstmt.setString(1, msg); // will not work for clobs messagesRS = pstmt.executeQuery(); while (messagesRS.next() && !logged) { String insertedMsg = (!getLogMessageBlobOption() ? messagesRS.getString(2) : lobToString(messagesRS.getBlob(2))); logged = msg.equals(insertedMsg); } } catch (SQLException | IOException e) { log.severe(e.getClass().getSimpleName() + " while getting slot " + " : " + e); e.printStackTrace(); } finally { cleanup(pstmt, messagesRS); cleanup(conn); } return logged; }
From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java
/** * Convert the specified column of the SQL ResultSet to the proper * java type.// w w w. ja v a2 s . c o m */ public Blob getBlob(ResultSet rs, int column) throws SQLException { return rs.getBlob(column); }
From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java
public boolean copyEpochFinalCheckpointState(String paxosID, int version) { if (isClosed() /* || !isLoggingEnabled() */) return true; boolean copied = false; // Stupid derby doesn't have an insert if not exist command String insertCmd = "insert into " + getPCTable() + " (version,members,slot,ballotnum,coordinator,state,create_time, paxos_id) values (?,?,?,?,?,?,?,?)"; String updateCmd = "update " + getPCTable() + " set version=?,members=?, slot=?, ballotnum=?, coordinator=?, state=?, create_time=? where paxos_id=?"; String cmd = this.existsRecord(getPCTable(), paxosID) ? updateCmd : insertCmd; String readCmd = "select version, members, slot, ballotnum, coordinator, state, create_time from " + getCTable() + " where paxos_id=?"; PreparedStatement readCP = null; ResultSet cpRecord = null; Connection conn = null;//from w w w . ja v a 2 s .c o m PreparedStatement insertCP = null; try { conn = this.getDefaultConn(); readCP = conn.prepareStatement(readCmd); readCP.setString(1, paxosID); cpRecord = readCP.executeQuery(); while (cpRecord.next()) { if (version != cpRecord.getInt("version")) break; insertCP = conn.prepareStatement(cmd); insertCP.setInt(1, version); insertCP.setString(2, cpRecord.getString("members")); insertCP.setInt(3, cpRecord.getInt("slot")); insertCP.setInt(4, cpRecord.getInt("ballotnum")); insertCP.setInt(5, cpRecord.getInt("coordinator")); if (getCheckpointBlobOption()) { insertCP.setBlob(7, cpRecord.getBlob("state")); } else insertCP.setString(6, cpRecord.getString("state")); insertCP.setLong(7, cpRecord.getLong("create_time")); insertCP.setString(8, paxosID); copied = (insertCP.executeUpdate() > 0); // conn.commit(); log.log(Level.INFO, "{0} copied epoch final state for {1}:{2}: [{3}]", new Object[] { this, paxosID, version, Util.truncate( (getCheckpointBlobOption() ? new String(cpRecord.getBytes("state"), CHARSET) : cpRecord.getString("state")), 32, 32) }); } } catch (SQLException | UnsupportedEncodingException sqle) { log.severe("SQLException while copying epoch final state for " + paxosID + ":" + version + " using [" + cmd + "]. This node may be unable to participate in future epochs for " + paxosID); sqle.printStackTrace(); } finally { cleanup(readCP, cpRecord); cleanup(insertCP); cleanup(conn); } return copied; }