List of usage examples for java.sql Statement getResultSet
ResultSet getResultSet() throws SQLException;
ResultSet
object. From source file:migration.Helper.java
/** * Sql to string array.//w w w .ja v a 2 s . c o m * * @param con * - a valid DriverManager connection is required * @param statement * statement is an SQL statement that is executed using * connection con * @param column * the column of the query resut to be stored in the retuning * array * @return a string array containing the values resulting from the statement * execution, found in column column * @throws SQLException * the sQL exception */ String[] sqlToStringArray(final Connection con, final String statement, final int column) throws SQLException { final String[] ret = new String[this.sqlGetLength(con, statement)]; final Statement s = con.createStatement(); s.execute(statement); final ResultSet rs = s.getResultSet(); if (rs != null) { int cheat = 0; while (rs.next()) { ret[cheat++] = rs.getString(column); } } s.close(); return ret; }
From source file:migration.Helper.java
/** * Sql get length./*from ww w .j av a2s. c o m*/ * * @param con * - a valid DriverManager connection is required * @param statement * is an SQL statement that is executed using connection con * @return the number of rows (int) in the result from the statement * execution */ int sqlGetLength(final Connection con, final String statement) { int ret = 0; try { final Statement s = con.createStatement(); s.execute(statement); final ResultSet rs = s.getResultSet(); if (rs != null) { while (rs.next()) { ret++; } } s.close(); // EndStatement } catch (final SQLException e) { e.printStackTrace(); } return ret; }
From source file:org.hyperic.hq.product.JDBCMeasurementPlugin.java
protected double getQueryValue(Metric jdsn, boolean logSql) throws MetricNotFoundException, PluginException, MetricUnreachableException { initQueries();//from w ww . j av a 2 s . c o m String query = getQuery(jdsn); String attr = jdsn.getAttributeName(); if (query == null) { //plugin bug or hq-plugin.xml typo bug String msg = "No SQL query mapped to: " + attr; throw new PluginException(msg); } //ignore case to allow the stanard case "Availability" boolean isAvail = attr.equalsIgnoreCase(AVAIL_ATTR); Properties props = jdsn.getProperties(); String url = props.getProperty(PROP_URL), user = props.getProperty(PROP_USER), pass = props.getProperty(PROP_PASSWORD); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = getCachedConnection(url, user, pass); stmt = conn.createStatement(); stmt.execute(query); // If the query executed without error, we don't care if any // results were returned. if (isAvail) { return Metric.AVAIL_UP; } int column = getColumn(jdsn); if (logSql) { _data = null; _sqlLog = getSqlRow(stmt); } else if (column != COL_INVALID) { rs = stmt.getResultSet(); if (rs != null && rs.next()) { return rs.getDouble(column); } else { throw new MetricNotFoundException(attr); } } if (_data != null) { return _data.doubleValue(); } return rs.getDouble(getColumnName(jdsn)); } catch (SQLException e) { // Remove this connection from the cache. removeCachedConnection(url, user, pass); if (isAvail) { log.debug("AVAIL_DOWN", e); return Metric.AVAIL_DOWN; } String msg = "Query failed for " + attr + ", while attempting to issue query " + query + ":" + e.getMessage(); //XXX these two are oracle specific. // Catch divide by 0 errors and return 0 if (e.getErrorCode() == DBUtil.ORACLE_ERROR_DIVIDE_BY_ZERO || e.getErrorCode() == DBUtil.POSTGRES_ERROR_DIVIDE_BY_ZERO) return 0; if (e.getErrorCode() == DBUtil.ORACLE_ERROR_NOT_AVAILABLE || e.getErrorCode() == DBUtil.POSTGRES_CONNECTION_EXCEPTION || e.getErrorCode() == DBUtil.POSTGRES_CONNECTION_FAILURE || e.getErrorCode() == DBUtil.POSTGRES_UNABLE_TO_CONNECT || e.getErrorCode() == DBUtil.MYSQL_LOCAL_CONN_ERROR || e.getErrorCode() == DBUtil.MYSQL_REMOTE_CONN_ERROR) throw new MetricUnreachableException(msg, e); throw new MetricNotFoundException(msg, e); } finally { returnCachedConnection(url, user, pass, conn); DBUtil.closeJDBCObjects(log, null, stmt, rs); } }
From source file:org.apache.ibatis.executor.resultset.FastResultSetHandler.java
protected ResultSet getNextResultSet(Statement stmt) throws SQLException { // Making this method tolerant of bad JDBC drivers try {//from w ww . j av a 2 s.c om if (stmt.getConnection().getMetaData().supportsMultipleResultSets()) { // Crazy Standard JDBC way of determining if there are more // results if (!((!stmt.getMoreResults()) && (stmt.getUpdateCount() == -1))) { return stmt.getResultSet(); } } } catch (Exception e) { // Intentionally ignored. } return null; }
From source file:org.apache.calcite.avatica.jdbc.JdbcMeta.java
public ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount, PrepareCallback callback) {// w w w. j a va 2 s .c om try { final StatementInfo info = statementCache.getIfPresent(h.id); if (info == null) { throw new RuntimeException("Statement not found, potentially expired. " + h); } final Statement statement = info.statement; // Special handling of maxRowCount as JDBC 0 is unlimited, our meta 0 row if (maxRowCount > 0) { AvaticaUtils.setLargeMaxRows(statement, maxRowCount); } else if (maxRowCount < 0) { statement.setMaxRows(0); } boolean ret = statement.execute(sql); info.resultSet = statement.getResultSet(); assert ret || info.resultSet == null; final List<MetaResultSet> resultSets = new ArrayList<>(); if (info.resultSet == null) { // Create a special result set that just carries update count resultSets.add( MetaResultSet.count(h.connectionId, h.id, AvaticaUtils.getLargeUpdateCount(statement))); } else { resultSets.add(JdbcResultSet.create(h.connectionId, h.id, info.resultSet, maxRowCount)); } if (LOG.isTraceEnabled()) { LOG.trace("prepAndExec statement " + h); } // TODO: review client to ensure statementId is updated when appropriate return new ExecuteResult(resultSets); } catch (SQLException e) { throw propagate(e); } }
From source file:de.innovationgate.webgate.api.jdbc.custom.JDBCSource.java
private ResultSet getTableResultSet(String folder, String specify, boolean updatable) throws SQLException { if (!_tables.containsKey(folder.toLowerCase())) { return null; }//from w w w.j a va 2 s .c om StringBuffer query = new StringBuffer(); query.append("SELECT * FROM " + folder); if (specify != null) { query.append(" WHERE ").append(specify); } Statement stmt = getConnection().createStatement(_resultSetType, (updatable ? ResultSet.CONCUR_UPDATABLE : ResultSet.CONCUR_READ_ONLY)); stmt.execute(query.toString()); ResultSet resultSet = stmt.getResultSet(); return resultSet; }
From source file:org.imos.abos.netcdf.NetCDFfile.java
public String getFileName(Instrument sourceInstrument, Timestamp dataStartTime, Timestamp dataEndTime, String table, String dataType, String instrument) { //SimpleDateFormat nameFormatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"); SimpleDateFormat nameFormatter = new SimpleDateFormat("yyyyMMdd"); nameFormatter.setTimeZone(tz);/*from w w w .j a v a2s . c o m*/ String filename = "ABOS_NetCDF.nc"; String deployment = mooring.getMooringID(); String mooringName = deployment.substring(0, deployment.indexOf("-")); if (instrument != null) { deployment += "-" + instrument; } if (sourceInstrument != null) { String sn = sourceInstrument.getSerialNumber().replaceAll("[()_]", "").trim(); deployment += "-" + sourceInstrument.getModel().trim() + "-" + sn; String SQL = "SELECT depth FROM mooring_attached_instruments WHERE mooring_id = " + StringUtilities.quoteString(mooring.getMooringID()) + " AND instrument_id = " + sourceInstrument.getInstrumentID(); logger.debug("SQL : " + SQL); Connection conn = Common.getConnection(); Statement proc; double depth = Double.NaN; try { proc = conn.createStatement(); proc.execute(SQL); ResultSet results = (ResultSet) proc.getResultSet(); results.next(); logger.debug("instrument lookup " + results); depth = results.getBigDecimal(1).doubleValue(); //depth = 30; logger.info("depth from database " + depth); proc.close(); } catch (SQLException ex) { java.util.logging.Logger.getLogger(AbstractDataParser.class.getName()).log(Level.SEVERE, null, ex); } deployment += "-" + String.format("%-4.0f", Math.abs(depth)).trim() + "m"; } if (mooringName.startsWith("SAZ")) { addTimeBnds = true; } if (authority.equals("IMOS")) { // IMOS_<Facility-Code>_<Data-Code>_<Start-date>_<Platform-Code>_FV<File-Version>_<Product-Type>_END-<End-date>_C-<Creation_date>_<PARTX>.nc // IMOS_ABOS-SOTS_20110803T115900Z_PULSE_FV01_PULSE-8-2011_END-20120719T214600Z_C-20130724T051434Z.nc filename = //System.getProperty("user.home") //+ "/" "data/" + authority + "_" + facility + "_" + dataType + "_" + nameFormatter.format(dataStartTime) + "_" + mooringName; if (table.startsWith("raw")) { filename += "_FV01"; } else { filename += "_FV02"; // its a data product from the processed table } filename += "_" + deployment + "_END-" + nameFormatter.format(dataEndTime) + "_C-"; filename = filename.replaceAll("\\s+", "-"); // replace any spaces with a - character filename += nameFormatter.format(new Date(System.currentTimeMillis())); Log.debug("try file name " + filename); if (multiPart) { int n = 1; String fnNext = filename + String.format("_PART%02d.nc", n); File fn = new File(fnNext); while (fn.exists()) { Log.info("File exists " + fn); n++; fnNext = filename + String.format("_PART%02d.nc", n); fn = new File(fnNext); } filename = fnNext; } else { filename += ".nc"; } } else if (authority.equals("OS")) { filename = "OS" + "_" + facility + "_" + deployment + "_D" + ".nc"; } System.out.println("Next filename " + filename); return filename; }
From source file:mom.trd.opentheso.bdd.helper.FacetHelper.java
/** * Cette focntion permet d'ajouter une nouvelle Facette * /*from w w w .j a va 2 s. c om*/ * @param ds * @param idThesaurus * @param idConceptParent * @param lexicalValue * @param idLang * @param notation * @return Id of Facet */ public int addNewFacet(HikariDataSource ds, String idThesaurus, String idConceptParent, String lexicalValue, String idLang, String notation) { int idFacet = -1; Connection conn; Statement stmt; ResultSet resultSet; lexicalValue = new StringPlus().convertString(lexicalValue); try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "select max(facet_id) from thesaurus_array where" + " id_thesaurus='" + idThesaurus + "'"; stmt.executeQuery(query); resultSet = stmt.getResultSet(); resultSet.next(); idFacet = resultSet.getInt(1); idFacet = idFacet + 1; query = "Insert into thesaurus_array " + "(facet_id, id_thesaurus, id_concept_parent, " + " notation)" + " values (" + idFacet + ",'" + idThesaurus + "'" + ",'" + idConceptParent + "'" + ",'" + notation + "')"; stmt.executeUpdate(query); addFacetTraduction(ds, idFacet, idThesaurus, lexicalValue, idLang); } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception if (!sqle.getMessage().contains("duplicate key value violates unique constraint")) { log.error("Error while adding Facet with value : " + lexicalValue, sqle); } } return idFacet; }
From source file:mom.trd.opentheso.bdd.helper.FacetHelper.java
/** * Cette fonction permet de savoir s'il a une traduction dans cette langue * //from w w w . j a v a 2 s. c om * @param ds * @param idFacet * @param idThesaurus * @param idLang * @return Objet class NodeConceptTree */ public boolean isTraductionExistOfFacet(HikariDataSource ds, int idFacet, String idThesaurus, String idLang) { Connection conn; Statement stmt; ResultSet resultSet; boolean existe = false; try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "select id from node_label" + " where" + " facet_id = " + idFacet + " and lang = '" + idLang + "'" + " and id_thesaurus = '" + idThesaurus + "'"; stmt.executeQuery(query); resultSet = stmt.getResultSet(); if (resultSet != null) { resultSet.next(); if (resultSet.getRow() == 0) { existe = false; } else { existe = true; } } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error while asking if Traduction of Facet exist : " + idFacet, sqle); } return existe; }
From source file:mom.trd.opentheso.bdd.helper.FacetHelper.java
/** * Cette fonction permet de rcuprer les Id des Concepts regroups dans cette Facette * * @param ds/*from w w w . j a va 2s . c om*/ * @param idFacet * @param idThesaurus * @return ArrayList of IdConcepts */ public ArrayList<String> getIdConceptsOfFacet(HikariDataSource ds, int idFacet, String idThesaurus) { Connection conn; Statement stmt; ResultSet resultSet; ArrayList<String> tabIdConcept = null; try { // Get connection from pool conn = ds.getConnection(); try { stmt = conn.createStatement(); try { String query = "SELECT id_concept" + " FROM thesaurus_array_concept WHERE" + " thesaurusarrayid = " + idFacet + " and id_thesaurus = '" + idThesaurus + "'"; stmt.executeQuery(query); resultSet = stmt.getResultSet(); tabIdConcept = new ArrayList<>(); while (resultSet.next()) { tabIdConcept.add(resultSet.getString("id_concept")); } } finally { stmt.close(); } } finally { conn.close(); } } catch (SQLException sqle) { // Log exception log.error("Error while getting IdConcepts of Facet : " + idFacet, sqle); } return tabIdConcept; }