List of usage examples for java.sql ResultSet getObject
Object getObject(String columnLabel) throws SQLException;
Gets the value of the designated column in the current row of this ResultSet
object as an Object
in the Java programming language.
From source file:com.netspective.axiom.sql.ResultSetUtils.java
public Map getResultSetSingleRowAsMap(ResultSet rs, boolean useLabelAsKey) throws SQLException { Map result = new HashMap(); if (rs.next()) { ResultSetMetaData rsmd = rs.getMetaData(); int colsCount = rsmd.getColumnCount(); for (int i = 1; i <= colsCount; i++) { result.put(/*from ww w . j a va 2 s .c om*/ useLabelAsKey ? rsmd.getColumnLabel(i).toLowerCase() : rsmd.getColumnName(i).toLowerCase(), rs.getObject(i)); } return result; } else return null; }
From source file:org.tradex.jdbc.JDBCHelper.java
/** * Issues a named parameter query using numerical binds, starting at 0. * @param sql The SQL// w ww .j a va2 s . com * @param binds The bind values * @return an Object array of the results */ public Object[][] templateQuery(CharSequence sql, Object... binds) { NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(ds); final List<Object[]> results = template.query(sql.toString(), getBinds(sql.toString().trim().toUpperCase(), binds), new RowMapper<Object[]>() { int columnCount = -1; @Override public Object[] mapRow(ResultSet rs, int rowNum) throws SQLException { if (columnCount == -1) columnCount = rs.getMetaData().getColumnCount(); Object[] row = new Object[columnCount]; for (int i = 0; i < columnCount; i++) { row[i] = rs.getObject(i + 1); } return row; } }); Object[][] ret = new Object[results.size()][]; int cnt = 0; for (Object[] arr : results) { ret[cnt] = arr; cnt++; } return ret; }
From source file:com.splicemachine.db.iapi.types.UserType.java
/** * @see DataValueDescriptor#setValueFromResultSet * * @exception SQLException Thrown on error *///from w ww . j a v a2 s. com public void setValueFromResultSet(ResultSet resultSet, int colNumber, boolean isNullable) throws SQLException { value = resultSet.getObject(colNumber); isNull = evaluateNull(); }
From source file:org.jtalks.poulpe.util.databasebackup.persistence.DbTableData.java
/** * The method prepares table's data in the shape and passes every {@link Row} into given RowProcessor. * // www . j a v a 2 s. c o m * @param processor * injected logic to perform some actions under passing rows. see details for {@link RowProcessor}. * @throws SQLException * if any errors during work with database occur. */ public void getData(final RowProcessor processor) throws SQLException { try { jdbcTemplate.query(SELECT_FROM + tableName, new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); Row row = new Row(); for (int i = 1; i <= columnCount; i++) { ColumnMetaData columnMetaData = ColumnMetaData.getInstance(metaData.getColumnName(i), SqlTypes.getSqlTypeByJdbcSqlType(metaData.getColumnType(i))); row.addCell(columnMetaData, rs.getObject(i)); } try { processor.process(row); } catch (RowProcessingException e) { throw new SQLException(e); } } }); } catch (DataAccessException e) { throw new SQLException(e); } }
From source file:com.micromux.cassandra.jdbc.JdbcRegressionTest.java
@Test public void testBlob() throws Exception { UUID blobId = UUID.randomUUID(); CassandraBlob blobValue = new CassandraBlob(RandomStringUtils.random(10)); String insert = "INSERT INTO " + TYPETABLE + " (id,blobValue,dataMapValue) " + " VALUES(" + blobId.toString() + ", ?, {'12345': bigintAsBlob(12345)});"; PreparedStatement statement = con.prepareStatement(insert); statement.setBlob(1, blobValue);/* www. ja v a 2s .c o m*/ statement.executeUpdate(); statement.close(); Statement select1 = con.createStatement(); String query = "SELECT blobValue FROM " + TYPETABLE + " WHERE id=" + blobId.toString() + ";"; ResultSet result = select1.executeQuery(query); result.next(); Blob blobResult = result.getBlob(1); assertEquals(blobValue, blobResult); Statement select2 = con.createStatement(); String query2 = "SELECT dataMapValue FROM " + TYPETABLE + " WHERE id=" + blobId.toString() + ";"; ResultSet result2 = select2.executeQuery(query2); result2.next(); Object mapResult = result2.getObject(1); assertTrue(mapResult instanceof Map); assertEquals("There should be 1 record in the map", 1, ((Map) mapResult).size()); assertNotNull("Entry for '12345' should be in the map", ((Map) mapResult).get("12345")); assertNull("Entry for '54321' should NOT be in the map", ((Map) mapResult).get("54321")); }
From source file:com.sun.licenseserver.License.java
/** * Retrieve a license from the database that belongs to the given * userID, contentID and shopID combination. * //from ww w.j ava 2s .co m * @param userID * @param contentID * @param shopID * @return * @throws LicenseServerException */ public static License getLicenseFromDatabase(String userID, String contentID, String shopID) throws LicenseServerException { m_log.finer("Entering Function.."); m_log.fine("Find license for user=[" + userID + "]contentID=[" + contentID + "]shopID=[" + shopID + "]"); ResultSet rs = null; License lic = null; Blob license = null; String id = ""; String mime = ""; String expression = "select license, id, mime from sunLsLicenses where contentId= '" + contentID + "' and shopId='" + shopID + "' and userId='" + userID + "'"; DatabaseHelper dbh = DatabaseHelper.getDatabaseHelper(); rs = dbh.executeStatementWithResults(expression); // The check below is not working. // We need to invoke the beforeFirst() function on the // result set after we have counted the number of entries in the result set. // The beforeFirst() method does not works and throws an exception. // A work around has to be found to reinstate this test. // // if (dbh.countNumberInResultSet(rs) > 1) { // m_log.severe("More than one license retrieved for a given userID, contentID and shopID combo"); // throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE, // "More than one license retrieved for a given userID, contentID and shopID combo"); // } try { if (rs != null && rs.next()) { ; license = rs.getBlob("license"); id = rs.getObject("id").toString(); mime = rs.getObject("mime").toString(); id = id == null ? "" : id; mime = mime == null ? "" : mime; lic = new License(id, userID, contentID, shopID, mime, license.getBinaryStream()); } dbh.releaseResultSetResources(rs); } catch (SQLException e) { m_log.severe("Error in retrieveing license from result set"); e.printStackTrace(); throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE, "Error in retrieveing license from result set"); } m_log.finer("Leaving Function.."); return lic; }
From source file:ips1ap101.lib.core.db.util.AgenteSql.java
public boolean isStoredProcedure(String sql) throws SQLException { Bitacora.trace(getClass(), "isStoredProcedure", sql); Object resultado;/*from w ww.j a va2 s. c o m*/ ResultSet resultSet; Object object; boolean is = false; if (sql != null) { String procedureName = BaseBundle.getName(sql); Object[] args = new Object[] { procedureName }; resultado = executeProcedure(DB.CHECK_PROCEDURE, args); if (resultado instanceof ResultSet) { resultSet = (ResultSet) resultado; if (resultSet.next()) { object = resultSet.getObject(1); is = BitUtils.valueOf(object); } } else if (resultado instanceof Number) { is = BitUtils.valueOf(resultado); } Bitacora.trace(procedureName + " " + is); } return is; }
From source file:DatabaseBrowser.java
public ResultSetTableModel(ResultSet rset) throws SQLException { Vector rowData;//from w ww . java 2 s. c om ResultSetMetaData rsmd = rset.getMetaData(); int count = rsmd.getColumnCount(); columnHeaders = new Vector(count); tableData = new Vector(); for (int i = 1; i <= count; i++) { columnHeaders.addElement(rsmd.getColumnName(i)); } while (rset.next()) { rowData = new Vector(count); for (int i = 1; i <= count; i++) { rowData.addElement(rset.getObject(i)); } tableData.addElement(rowData); } }
From source file:fr.gael.dhus.database.liquibase.CopyProductImages.java
@Override public void execute(Database database) throws CustomChangeException { PreparedStatement products = null; ResultSet products_res = null; JdbcConnection db_connection = (JdbcConnection) database.getConnection(); try {// ww w . j a v a2 s.co m products = db_connection.prepareStatement("SELECT ID,QUICKLOOK,THUMBNAIL FROM PRODUCTS"); products_res = products.executeQuery(); while (products_res.next()) { PreparedStatement copy_blob_stmt = null; ResultSet generated_key_res = null; try { Blob ql = (Blob) products_res.getObject("QUICKLOOK"); Blob th = (Blob) products_res.getObject("THUMBNAIL"); Long pid = products_res.getLong("ID"); // No images: add false flags if ((ql == null) && (th == null)) { PreparedStatement product_flags_stmt = null; // Add related flags try { product_flags_stmt = db_connection.prepareStatement( "UPDATE PRODUCTS SET THUMBNAIL_FLAG=?,QUICKLOOK_FLAG=? " + "WHERE ID=?"); product_flags_stmt.setBoolean(1, false); product_flags_stmt.setBoolean(2, false); product_flags_stmt.setLong(3, pid); product_flags_stmt.execute(); } finally { if (product_flags_stmt != null) try { product_flags_stmt.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } continue; } copy_blob_stmt = db_connection.prepareStatement( "INSERT INTO PRODUCT_IMAGES (QUICKLOOK,THUMBNAIL) " + "VALUES (?,?)", Statement.RETURN_GENERATED_KEYS); copy_blob_stmt.setBlob(1, ql); copy_blob_stmt.setBlob(2, th); copy_blob_stmt.execute(); generated_key_res = copy_blob_stmt.getGeneratedKeys(); if (generated_key_res.next()) { PreparedStatement set_product_image_id_stmt = null; Long iid = generated_key_res.getLong(1); // Add ProductImages "IMAGES" entry in product try { set_product_image_id_stmt = db_connection .prepareStatement("UPDATE PRODUCTS SET IMAGES_ID=?, THUMBNAIL_FLAG=?, " + "QUICKLOOK_FLAG=? WHERE ID=?"); set_product_image_id_stmt.setLong(1, iid); set_product_image_id_stmt.setBoolean(2, th != null); set_product_image_id_stmt.setBoolean(3, ql != null); set_product_image_id_stmt.setLong(4, pid); set_product_image_id_stmt.execute(); } finally { if (set_product_image_id_stmt != null) try { set_product_image_id_stmt.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } } else { logger.error("Cannot retrieve Image primary key for " + "product ID #" + products_res.getLong("ID")); } } finally { if (generated_key_res != null) try { generated_key_res.close(); } catch (Exception e) { logger.warn("Cannot close ResultSet !"); } if (copy_blob_stmt != null) try { copy_blob_stmt.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } } } catch (Exception e) { throw new CustomChangeException("Cannot move Blobs from product", e); } finally { if (products_res != null) { try { products_res.close(); } catch (Exception e) { logger.warn("Cannot close ResultSet !"); } } if (products != null) { try { products.close(); } catch (Exception e) { logger.warn("Cannot close Statement !"); } } //if (db_connection!=null) try { db_connection.close (); } // catch (Exception e) {} } }
From source file:com.netspective.axiom.value.source.QueryResultsValueSource.java
public Value getQueryResults(ValueContext vc, int style) { ValueSources.getInstance().assertValueContextInstance(DatabaseConnValueContext.class, vc, this); DatabaseConnValueContext dcvc = (DatabaseConnValueContext) vc; SqlManager sqlManager = null;//from w w w.ja v a 2 s . com try { sqlManager = getSqlManager(dcvc); if (sqlManager == null) throw new RuntimeException("Unable to locate SQL Manager for " + this); } catch (Exception e) { log.error("Error retrieving SQL Manager", e); throw new NestableRuntimeException(e); } Query query = sqlManager.getQuery(queryId); if (query == null) { log.error("Unable to locate Query '" + queryId + "' in SQL Manager '" + sqlManager + "' in " + this + ". Available: " + sqlManager.getQueries().getNames()); if (style == RESULTSTYLE_PRESENTATION) { PresentationValue pValue = new PresentationValue(); PresentationValue.Items items = pValue.createItems(); items.addItem("Unable to find query " + queryId); return pValue; } else return new GenericValue("Unable to find query " + queryId); } String dataSourceIdText = dataSourceId != null ? dataSourceId.getTextValue(vc) : null; QueryResultSet qrs = null; try { if (params == null) qrs = query.execute(dcvc, dataSourceIdText, null); else { Object[] parameters = new Object[params.length]; for (int p = 0; p < params.length; p++) parameters[p] = params[p].getValue(vc).getValueForSqlBindParam(); qrs = query.execute(dcvc, dataSourceIdText, parameters); } } catch (Exception e) { log.error("Error executing query", e); throw new NestableRuntimeException(e); } Value value = null; try { ResultSet rs = qrs.getResultSet(); switch (style) { case RESULTSTYLE_SINGLECOLUMN_OBJECT: if (rs.next()) value = new GenericValue(rs.getObject(1)); else value = null; break; case RESULTSTYLE_FIRST_ROW_MAP_OBJECT: if (rs.next()) { Map rowMap = new HashMap(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) rowMap.put(rsmd.getColumnName(i), rs.getObject(i)); value = new GenericValue(rowMap); } else value = null; break; case RESULTSTYLE_ALL_ROWS_MAP_LIST: List rows = new ArrayList(); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { Map rowMap = new HashMap(); for (int i = 1; i <= rsmd.getColumnCount(); i++) rowMap.put(rsmd.getColumnName(i), rs.getObject(i)); rows.add(rowMap); } value = new GenericValue(rows); break; case RESULTSTYLE_FIRST_ROW_LIST: rsmd = rs.getMetaData(); if (rs.next()) { List row = new ArrayList(); for (int i = 1; i <= rsmd.getColumnCount(); i++) row.add(rs.getObject(i)); value = new GenericValue(row); } else value = null; break; case RESULTSTYLE_ALL_ROWS_LIST: rsmd = rs.getMetaData(); rows = new ArrayList(); while (rs.next()) { List row = new ArrayList(); for (int i = 1; i <= rsmd.getColumnCount(); i++) row.add(rs.getObject(i)); rows.add(row); } value = new GenericValue(rows); break; case RESULTSTYLE_RESULTSET: value = new GenericValue(qrs); break; case RESULTSTYLE_PRESENTATION: PresentationValue pValue = new PresentationValue(); PresentationValue.Items items = pValue.createItems(); rsmd = rs.getMetaData(); rows = new ArrayList(); switch (rsmd.getColumnCount()) { case 1: while (rs.next()) items.addItem(rs.getString(1)); break; default: while (rs.next()) items.addItem(rs.getString(1), rs.getString(2)); break; } value = pValue; break; default: throw new RuntimeException("Invalid style " + resultStyle + " in " + this); } } catch (Exception e) { log.error("Error retrieving results", e); throw new NestableRuntimeException(e); } finally { if (resultStyle != RESULTSTYLE_RESULTSET) { try { if (qrs != null) qrs.close(true); } catch (SQLException e) { log.error("Error closing result set", e); throw new NestableRuntimeException(e); } } } return value; }