Subset of a ResultSet

I am trying to optimise my Database code. At step one I make a fetch on the data by getting all the info about all States in my Country table. Now having got a reference to this resultSet, I want to narrow down the ResultSet to contain rows only for the States that the user has selected.
Can anyone please suggest some way to do this without firing another query to the database.
I could have done this using a scrollable ResultSet and manipulated the data, but I don't want to. I just want to narrow down the ResultSet dynamically such that the ResultSet I get after narrowing down contains only the data for these states.

The user is selecting specific states but you are then getting the data for all the states anyways?
That is inefficient. And misses the point of using a database in the first place.
But if you must...
You have to create a loop that goes though all of the data. For each row you compare it to the data you have. If it matches you keep it. If it doesn't you discard it.
Once done with the loop you return the data you kept.

Similar Messages

  • Fastest way to select subset of a resultset?

    I have a query which I use to load a result set in Java 1,000 records each time., it looks like this:
    select DATA_CLOB as msg from
    (select DATA_CLOB, rownum as rn from msg_data where batch_id = ? and category = ? order by msg_data_id)
    where rn between ? and ?
    When the number of records for a given batch_id,category are small, say a few tens of thousands, its never been a problem
    But just recently it had to deal with one batch where there was 1.5 M records and this query is killing us, it's been 3 DAYS now and its not done yet!
    There are proper indexes on the columns selected from, and confirmed with Explain Plan that the plan is only doing indexed searches.
    Was the way we do the between 2 rownum indexes poor design?
    Is there a more efficient way?
    Other way I was thinking was maybe just do where rownum < 1000 each time instead of maintaining an index range which is incremented by a thousand each time.
    In either case I have both that select and an update which updates a timestamp on the rows that were processed, so I could use that in the where rownum < 1000 query to filter out rows already processed.
    Can you think of any other ways to do this quicker?
    Again, the sole purpose is to basically iterate through a subset of records from table, 1,000 at a time.

    trant wrote:
    I have a query which I use to load a result set in Java 1,000 records each time., it looks like this:
    select DATA_CLOB as msg from
    (select DATA_CLOB, rownum as rn from msg_data where batch_id = ? and category = ? order by msg_data_id)
    where rn between ? and ?
    When the number of records for a given batch_id,category are small, say a few tens of thousands, its never been a problem
    But just recently it had to deal with one batch where there was 1.5 M records and this query is killing us, it's been 3 DAYS now and its not done yet!Not surprising.
    It's having query all the data (including your CLOB data by the looks of it) and then order all that data before it picks out just the 1,000 rows you want.
    What is the business process you are trying to achieve by doing this?
    Seems odd that you want to query back 1,000 clobs of data at a time over the network to your java application.
    Other way I was thinking was maybe just do where rownum < 1000 each time instead of maintaining an index range which is incremented by a thousand each time.Still, if it's got to order the data first, it's going to take time.
    In either case I have both that select and an update which updates a timestamp on the rows that were processed, so I could use that in the where rownum < 1000 query to filter out rows already processed.
    Can you think of any other ways to do this quicker?
    Again, the sole purpose is to basically iterate through a subset of records from table, 1,000 at a time.Why? For what purpose?

  • Creating subset of ResultSet

    I'm working with a product that uses a jdbc driver, but it isn' jdbc 2.0. It's an earlier version, although I'm not sure; probably the version before 2.0. I need to grab a subset of a resultset (all the rows, but only some of the columns). What's the easiest way of doing this? Thanks.

    Easiest way of doing that is to use the ResultSet as
    is and ignore the columns you don't want. Or am I
    missing something?I thought there might be something similar to getArray (jdbc 2.0 method). I have to filter a couple of different looking resultsets, and thought there might be an easy way to do this, without looping through the whole resultset and picking out only what I need.

  • JTable and ResultSet TableModel with big resultset

    Hi, I have a question about JTable and a ResultSet TableModel.
    I have to develop a swing JTable application that gets the data from a ResultSetTableModel where the user can update the jtable data.
    The problem is the following:
    the JTable have to contain the whole data of the source database table. Currently I have defined a
    a TYPE_SCROLL_SENSITIVE & CONCUR_UPDATABLE statement.
    The problem is that when I execute the query the whole ResultSet is "downloaded" on the client side application (my jtable) and I could receive (with big resultsets) an "out of memory error"...
    I have investigate about the possibility of load (in the client side) only a small subset of the resultset but with no luck. In the maling lists I see that the only way to load the resultset incrementally is to define a forward only resultset with autocommit off, and using setFetchSize(...). But this solution doesn't solve my problem because if the user scrolls the entire table, the whole resultset will be downloaded...
    In my opinion, there is only one solution:
    - create a small JTable "cache structure" and update the structure with "remote calls" to the server ...
    in other words I have to define on the server side a "servlet environment" that queries the database, creates the resultset and gives to the jtable only the data subsets that it needs... (alternatively I could define an RMI client/server distribuited applications...)
    This is my solution, somebody can help me?
    Are there others solutions for my problem?
    Thanks in advance,
    Stefano

    The database table currently is about 80000 rows but the next year will be 200000 and so on ...
    I know that excel has this limit but my JTable have to display more data than a simple excel work sheet.
    I explain in more detail my solution:
    whith a distribuited TableModel the whole tablemodel data are on the server side and not on the client (jtable).
    The local JTable TableModel gets the values from a local (limited, 1000rows for example) structure, and when the user scroll up and down the jtable the TableModel updates this structure...
    For example: initially the local JTable structure contains the rows from 0 to 1000;
    the user scroll down, when the cell 800 (for example) have to be displayed the method:
    getValueAt(800,...)
    is called.
    This method will update the table structure. Now, for example, the table structure will contain data for example from row 500 to row 1500 (the data from 0 to 499 are deleted)
    In this way the local table model dimension will be indipendent from the real database table dimension ...
    I hope that my solution is more clear now...
    under these conditions the only solutions that can work have to implement a local tablemodel with limited dimension...
    Another solution without servlet and rmi that I have found is the following:
    update the local limited tablemodel structure quering the database server with select .... limit ... offset
    but, the select ... limit ... offset is very dangerous when the offset is high because the database server have to do a sequential scan of all previuous records ...
    with servlet (or RMI) solution instead, the entire resultset is on the server and I have only to request the data from the current resultset from row N to row N+1000 without no queries...
    Thanks

  • New GeoRaptor release !

    Hello List,
    A new release of the GeoRaptor plugin is ready ! Version 20100524 is available for download on the project's sourceforge page : [http://sourceforge.net/projects/georaptor/] Update center : [Update Center|http://georaptor.sourceforge.net/install.xml]
    GeoRaptor is a SQLDeveloper plugin to view Oracle Spatial data and assist in creating/validating Spatial data and indexes.
    This current release (20100525) release includes these changes:
    - GeoRaptor now handles Tables/Views and Materialized Views.
    - Initiation of GeoRaptor functions can occur at the table or column level in the SQL Developer connection tree; (ie a GeoRaptor context menu has been added to the Columns of a table/view)
    - The way the sdo_geometry structure attribute is displayed has been re-written to handle xD data with slightly improved colouration (more to come).
    - There is now the ability to display an sdo_geometry attribute in a query result table as SDO_GEOMETRY/WKT/KML or GML2/GML3.
    - The dropping of a spatial index (for tables/materialized views) can now be done via a new context menu option.
    - The way the sdo_geometry data is displayed in the spatial view has been re-written. It will draw 2D, 3/4D (Z or M or both) data but only in 2D.
    - The way sdo_geom_metadata is handled and updated has been overhauled. Tables with multiple geometries can be dealt with in the one metadata panel.
    - Spatial indexing has been improved.
    - There is a Suffix/Prefix (called Affix) Tools>GeoRaptor>Preferences preferences for controlling its placement.
    - GeoRaptor can discover the layer_gtype parameter (from either all the data or from a sample).
    - Setting the sdo_indx_dims parameter can be done via a pulldown; as also whether the index is geodetic (tick box)
    - Setting the TABLESPACE parameters has also been added.
    - GeoRaptor can now be told to position a new table/sdo_geometry object (Add to Spatial View) in the spatial view at the top of the layer tree or at the bottom (Tools>Preferences>GeoRaptor)
    - The ability to move an existing layer in the spatial view to the the TOP or BOTTOM has been added via a right mouse click menu entry.
    - Similarly, you can now tell GeoRaptor where to put the layer list in the view: in the RIGHT or LEFT panel.
    - The position of the dividers in the spatial view now are trapped and saved.
    - The geometry spatial validation routines have been modified to allow for tolerance or diminfo based validation. Multiple geometries per table are handled. The user can now select their own primary key (including multiple columns) they would like to use in the output report.
    - GeoRaptor can now draw arrows at the midpoint of each segment in a linestring or just at the end.
    - GeoRaptor can process (ie visualise) data as STRUCT or JGeometry (a user preference controls this).
    - A comprehensive and flexible shapefile loading component has been added that handles multiple shapefiles, various attribute sets, changing of string attributes to numbers etc.
    Enhancements:
    - Code quality improvements are already being prepared.
    - The next release already has ready to go enhancements to the shapefile loader.
    - The ability to create (automatically) a single sdo_geom_metadata entry that covers all shapefiles in a shapefile set that is loaded into a single table.
    - Similarly a basic spatial index can be built at the end of a load run.
    - The ability to round the ordinate values read from each shapefile's X,Y, Z etc double precision ordinates. So, an shapefile X value of 234567.97456362839 can be written as 234567.975 if a decimal place rounding of 3 is chosen.
    - More options or colouring SDO_GEOMETRY data in a resultset;
    - Ability to colourize SDO_DIM_ARRAY, VERTEX_TYPE etc structures;
    - Support the mapping (add to spatial view) of a SQL query resultset (viewed currently only by styling the sdo_geometry attribute).
    - This will include the ability to select a subset of the resultset for visualisation, copying to clipboard, export (not just one at a time as in the current version). In fact, working with resultsets will become the main focus of how GeoRaptor will work in the future.
    - Add a new Spatial node to SQL Developer that collects up all tables etc with spatial data in one node (like Tables/Views/Materialized Views etc) so we can initiate action from there minimising mouse movement and increasing end user productivity.
    - Create a tool for discovering and removing stale sdo_geom_metadata records.
    - Support projections in the map view;
    - Support multiple independent map views (not just one);
    - Support WMS layers within the map view;
    - Provide spatial data export (shapefiles first);
    - Support limited visualisation of external shapefile data before loading eg to view to display with existing Oracle data.
    - Network topology visualisation and functionality;
    - Export functionality
    We encourage you to use GeoRaptor and discover its usefulness. We are spatial professionals who use SQL Developer every day in our business and consulting activities: we want the tool to make our lives easier and we hope they will do that for you too.
    However, we don't know how you use GeoRaptor and SQL Developer so we would love to hear your wishes for the product and the sorts of improvements would help you in your work and use: [Feature Requests|https://sourceforge.net/tracker/?group_id=158162&atid=806731]
    Like all software GeoRaptor is not perfect: the software contains bugs.
    Please help us in recognizing and fixing those bugs by reporting them : [Bug tracker|https://sourceforge.net/tracker/?group_id=158162&atid=806728]
    Now that we have a release out, we intend on making regular bug fix release and not just releases containing new functionality.
    The GeoRaptor team
    Edited by: Olaf I. on Jun 8, 2010 5:58 AM : a more comprehensive list of what's new !

    This release is really great. Simon uses the term "we" but he has probably done 99% of all the enhancements that have gone into this release.
    Thanks a lot for the effort Simon!!

  • How to display 5 record.

    Hi,
    In Result Set there is 1,00,000 & it displays
    out of memory message i want to display only 5 records on page & extract only
    5 record from query..
    2. Is there any method to find out page size..

    But i want to show all record by useing previous next
    button..
    and i am not able to get all record because may they
    are 1,00,000
    thats the problem..You should handle this in SQL, most databases has a way to retreive only a subset of a resultset.
    /Kaj

  • Returning a subset of rows through a ResultSet WITHOUT rownum?

    I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
    My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
    1. Get SQL from TOPLink
    2. Pass SQL through a Statement
    3. Get resulting ResultSet
    At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
    Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
    Thanks,
    Michael Allen
    [email protected]

    Hi Michael,
    Is there some sort of selection criteria in which you could use return the required 200-250 rows of data? If so, I would embed that into the TopLink query.
    Another option is using the ORDER BY operator. Without order, constructing a query of elements 200-250 twice would not guarentee that they would be the same elements.
    You can also construct your own SQL statement and execute it directly on a TopLink session.
    Darren Melanson
    Strategic Implementation Consultant
    Oracle Canada.
    I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
    My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
    1. Get SQL from TOPLink
    2. Pass SQL through a Statement
    3. Get resulting ResultSet
    At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
    Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
    Thanks,
    Michael Allen
    [email protected]

  • Getting # of rows returned in JDBC resultset

    Hi,
    Is there an easy call to get the number of rows in a resultset?
    Right now I want to display en entire record if there's only one and display only a subset of record info if there's more than one.
    I ended up doing the following:
    while(rs.next()) {
    i++);
    then I call rs.beforeFirst(); to get back to the beginning of the result set and set my conditionals to operate on the "i" variable I created before.
    There must be a rs.maxcount() or something to that effect isn't there? I'm using a JDBC2.0 type 4 postgreSQL driver. It supports Datasourcing, but not much else.
    Frank

    Hi,
    You can do it in two ways,
    1. As stated above, you can do it.
    For more information,
    http://java.sun.com/j2se/1.3/docs/api/java/sql/ResultSet.html
    2.You can use a seperate prepared statement that returns nothing but a count of the rows that will be selected. i.e. select count(*) from Table,
    Instead of * you can also use any column existing in Table.
    Hope this helps.
    Best Luck!
    Senthil Babu J

  • SUBSET OF RECORDS

    given
    "SELECT * FROM BLAH" returns 2,000,000 records
    that i want to display them in 1000 record pages
    a fresh query must be made for each page
    is there a best practice for getting say records 10000 -> 11000
    without having to get a complete resultset and seeking to 10000

    Nei, yes there are ways to extract a small subset of records though some coding may be required:
    With version 8.1+ the exp utility has the ability to add a where clause condition to the export but only one query is allowed that must work for every table in the export set.
    You can create a database link on the test system and select from production only those rows you want across the link.
    You can query the tables and spool a delimited file of the desired output and use sqlldr to insert the data into test.
    HTH -- Mark D Powell --

  • How do I add a subset of records to a set of records?

    I have a result set of consultants and branch offices and I need to add a subset of employees to each branch office.
    I added an Employee[ ] subset to my consultant getter/setters. A PL/SQL package returns a cursor result set
    of consultants and branch offices and another cursor result set of employees. Each employee is assigned an
    office ID and each consultant and branch office is assigned an office ID.
    I am unsure in Java how to traverse the employee result set to get each subset of employees with the correct office.
    Here is the code that calls the PL/SQL and loads my vector array with consultants and branch offices:
        public Consultant[] getConsultants(String pvConsultant_Firm,
                                            String pvAddr_City_Main,
                                            String pvAddr_State_Main,
                                            String pvAddr_Zip_Main, 
                                            String pvAddr_City_Branch,
                                            String pvAddr_State_Branch,
                                            String pvAddr_Zip_Branch,
                                            String pvResidency,
                                            String pvFirst_Name,    
                                            String pvLast_Name,
                                            String pvOrder_By_Office,
                                            String pvOrder_By_Employee,
                                            String display_Branch,
                                            String display_Employee)
          Vector retval = new Vector();
          DBConnection conn = new DBConnection();
          CallableStatement cstmt = conn.prepareCall("begin " + PACKAGE + "Get_Consultant_Cursors(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);end;");
          ResultSet rsConsultant;
          ResultSet rsEmployee;
          Consultant curConsult;
          Employee curEmployee;
          try
             if(cstmt!=null)
                String Consult_Type = null;
                if ("true".equalsIgnoreCase(display_Branch) ||
                     "true".equalsIgnoreCase(display_Employee)){
                   Consult_Type = null;
                else {
                   Consult_Type = "MAIN";
                cstmt.setString("pvConsultant_Firm", pvConsultant_Firm);
                cstmt.setString("pvOffice_Type", Consult_Type);
                cstmt.setString("pvAddr_City_Main", pvAddr_City_Main);
                cstmt.setString("pvAddr_State_Main", pvAddr_State_Main);
                cstmt.setString("pvAddr_Zip_Main", pvAddr_Zip_Main);
                cstmt.setString("pvAddr_City_Branch", pvAddr_City_Branch);
                cstmt.setString("pvAddr_State_Branch", pvAddr_State_Branch);
                cstmt.setString("pvAddr_Zip_Branch", pvAddr_Zip_Branch);
                cstmt.setString("pvResidency", pvResidency);
                cstmt.setString("pvFirst_Name", pvFirst_Name);
                cstmt.setString("pvLast_Name", pvLast_Name);
                cstmt.setString("pvOrder_By_Employee", pvOrder_By_Employee);
                cstmt.setString("pvOrder_By_Office", pvOrder_By_Office);
                cstmt.registerOutParameter("pcurConsultant_Office", OracleTypes.CURSOR);
                cstmt.registerOutParameter("pcurConsultant_Employee", OracleTypes.CURSOR);
                cstmt.execute();
                rsConsultant = (ResultSet)cstmt.getObject("pcurConsultant_Office");
                rsEmployee = (ResultSet)cstmt.getObject("pcurConsultant_Employee");
                while(rsConsultant.next())
                    curConsult = getConsultant(rsConsultant);
                    retval.add(curConsult);
                     if ("true".equalsIgnoreCase(display_Employee)){
    HOW DO I HANDLE THIS?
                 rsConsultant.close();
                 conn.closeCstmt(cstmt);
              catch (SQLException e)
                 conn.logToFile(this, "getConsultants()", e);
              conn.close();
           return (Consultant[])retval.toArray(new Consultant[retval.size()]);
        }

    It will basically look something like this:
    Consultant A           Main Office
                                                 Employee 1
                                                 Employee 2
                                                 Employee 3
                           Branch A       
                                                 Employee 4
                                                 Employee 5
                           Branch B
                                                 Employee 6
                                                 Employee 7
    Consultant B           Main Office
                                                 Employee 8
                                                 Employee 9
                           Branch A       
                                                 Employee 10
                                                 Employee 11The consultant and branch offices are in one result set and the employees are in another. I need to combine them
    so I can return them and display them as above in my JSP.

  • Best way to store data obtained from a resultset !?

    Hi all,
    I am working on a verification process that is to be run on our DB upon every external db extraction prior to merge into our DB (which is being done manually now)
    What I have decided so far is to have a verifier interface that is implemented by a bunch of *Verifier classes.
    Then depending on the level of verification, a subset of these verifiers would run and populate a generic result object (per verifier) with the query results and whether the verifier passed or not.
    I was thinking of having the Result class employ a JTable to store the query result (from a resultset), but I can't seem to find a way to retrieve the data from the Jtable row by row (I'd like to obtain the result from the JTable row by row as it would be easy to format) or the entire table to display for that matter.
    Please advise if you think this is a good approach? and if JTable's a good idea!? if yes, how should i use it? otherwise, what would you suggest?
    Thanks a lot,
    Cheers,
    parachuter2b

    BigDaddyLoveHandles wrote:
    There's no need for a "table". Use a List<YourBusinessClass>. If you don't know collections take the tutorial:
    |http://java.sun.com/docs/books/tutorial/collections/index.html]Thanks, that's what I sort of did:
    I figured how to use the ResultSetMetaData to get the column names and therefore generate a report from any query by having its resultset.
    so created a Result class, which holds the resultset of the query, plus a boolean that indicates whether the verification passed or not.
    Now what I have problem with is formatting the resultset and displaying it nicely in a report. The problem is that the length of the values in the resultset are variable and using constant indentation doesn't work. What's the easiest way to get around this apart from going through the resultset once before displaying the report to calculate the indentations for every single item?
    Thanks,
    parachuter2b

  • How do I get a subset of a result set

    I am getting a result set from a remote data source. After the resultset is returned how can I do a select on the result to return a subset of records?
    My code:
    package com.drawingpdmw1;
    import java.sql.*;
    import com.ibm.as400.access.*;
    * @author sde
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    public class getLastDashNumberConnection {
         public String errorString;
         public String literalerrorString;
         public String maxRecSeq;
         public getLastDashNumberConnection(String arg0) {
                      AS400JDBCDataSource datasource = new AS400JDBCDataSource("gvas400");
                 datasource.setTranslateBinary(true);
                 datasource.setUser("drawchg");
                 datasource.setPassword("webabc1");
                 try{
                      Connection connection = datasource.getConnection();
                     Statement stmt = connection.createStatement();
                     String sql = "select distinct dmdrawno from webprddt6.drawmext3 Where dmdrawno LIKE '%" + arg0.substring(0,6) + "%'";
                     ResultSet rs = stmt.executeQuery(sql);
                     while(rs.next()){
                          System.out.println(rs.getString("dmdrawno").trim());
                     errorString = "";
                     literalerrorString = "NoError";
                 catch(SQLException sqle){
                      System.out.println("Error");
                      System.out.println(sqle);
                      errorString = "Warning!!! A New Dash Number could not be created!";
                       literalerrorString = "Error";
    }

    First, thanks for the info on closing my objects.
    Now as far as the data here is my situation. The purpose of this class is to return the next dash number that can be used for a series of partnumbers. In most cases the series is constructed with only one type of dash numbers. Example: -401, -403, -405 dashes that start with a 4 are assemblies. This is easy to figure out the nex dash(-407).
    However, some of our partnumber series have dashes like -001, -003, -005 which are detail level part numbers along with the -401 etc.
    Now a user needs to create a new dash number. First, is this a detail dash or an assy dash. My idea is to get all the possibilites for a series, check for dash types, then return the next dash for each type.

  • ResultSet.absolute(int) Performance Issue

    I'm using the Oracle driver. I've run some tests and it appears that:
    ResultSet rs = ...;
    rs.absolute(n);
    has approximately the same performance as:
    ResultSet rs = ...;
    for (int i = 0; i < n; i++)
    rs.next();
    Is this all it is doing? For large values of "n" this could be very bad.
    I'd use "ROWNUM", but I also use an O/R framework. The only way to
    pull out specific subsets is to use JDBC scrolling. Is there anything I
    can do?
    Thanks,
    Bob

    Bob Lee wrote:
    There are at least 4 oracle driver vendors and
    multiple versions from each, so let us know
    which one you're using. See more below...I've tried the Oracle OCI (thick) and thin drivers, version 9.
    It certainly may be doing this. Very few drivers would go to the
    DBMS for each row individually, in a random access fashion.
    The driver would probably obtain and buffer all the intermediate
    rows that had not been fetched.This sucks. If I call ResultSet.absolute(), I probably don't need all of
    the intermediate rows.But you asked for them, so the driver and DBMS think you probably
    want them. Absolute() is part of implementing random access. It would
    never be interpreted as 'I don't want (some) rows'. It can be called to
    go backwards from the current position too.
    Clever SQL can be made to select the subsets (contiguous ranges) you want, one by oneDamn.It's a solution.... This sounds like something you want to do in a stored procedure.
    The cardinal performance problem in RDBMS applications is shipping scads of
    raw data out of the DBMS to the client, to be processed and/or discarded, instead
    of processing the raw stuff where it is in the DBMS.
    Good luck,
    Joe
    >
    Thanks,
    Bob
    Thanks,
    Bob

  • Mysterious closing ResultSets

    I'm getting desperate for a solution to this problem (as is the rest of the development team!).
    Basically we've been trying to create a system that automatically assigns values (frequencies) to objects (nodes) based on a rule set. Each node contains a varying number of sub-objects (radios) and each radio needs one frequency. The database has been set up and has test data for our Solution class to go through. However, we've run into an odd problem where our ResultSets are suddenly closing.
    The classes work like this:
    Database Broker (handles connection to DB, as well as executeQuery and executeUpdate statements.)
    Entry Broker (Holds all SQL statements for data retrieval in various methods. Each method contains an SQL statement to access data, and code to format that data into something useable by the main class.
    Solution/Main class (Contains methods to use the data from the Entry Broker to test valid solutions. Certain rules apply to assigning frequencies to radios and this class ensures that the data applies to these rules before it writes the data back to the DB (via the EntryBroker).
    The problem we continually run into is that whilst the ResultSets work fine in the Entry Broker, they are closed when they return to the Main class.
    Here's the catch: It seems in most cases that only the FIRST ResultSet returned in each method is closed, the remaining ResultSets work fine. We worked around this problem by creating a 'dummy' ResultSet, which obtained data from the database which was never used (the project name). We put this in its own try catch bracket so it would not interrupt the project.
    It worked fine for a few classes, but for others (notably the following one) it was ineffective. We've searched and searched but we cannot find anyone with a similar complaint (except a few people who have commented about ODBC version problems). Our ODBC version is 3.520.7713.0
    Here's an example method from the Solution class (The entire class is over 1000 lines):
    // Method to test Harmonic resonance for nodes within 10m
    private boolean resonanceGlobal (boolean tstResonanceG, double txFreq, double rxFreq, int distance)     {
    System.out.println("Beginning global harmonic resonance check");
    try {
    // Getting Nodes
    rsNode2 = eBroker.getNodes(projectNo);
    // node loop
    while (rsNode2.next())     {
    System.out.println("602 Test Marker GHarm 1");
    // get next node, store in nodeTemp
    nodeTemp = rsNode2.getInt(1);
    // System out to show which nodes will pass if statement
    System.out.println(node + " compare to " + nodeTemp);
    // avoid testing the same node against itself
    if (nodeTemp != node)     {
    // distance check (only neccesary within 10m)
    System.out.println("Test Marker Before Distance check");
    distance = getDistance(node, nodeTemp, distance);
    System.out.println("Test Marker After Distance check");
    // distance check if statement
    if (distance <= 10)     {
    System.out.println("618 Test Marker GHarm 2");
    // get the radios of the node, foreign node
    rsRadiosTemp = eBroker.getRadios(node);
    rsDummy = eBroker.getDummy(projectNo);
    rsRadios2 = eBroker.getRadios(nodeTemp);
    // This dummy ResultSet normally fails so that
    // the other ResultSets perform normally
    try {
    rsDummy.next();
    }     // end try
    catch (java.sql.SQLException dummyException)     {
    System.out.println("dummyException " + dummyException);
    }     // end catch
    // radio loop
    while (rsRadiosTemp.next())     {     // error occurs here
    System.out.println("627 Test Marker GHarm 3");
    // loop for foreign node radios
    while (rsRadios2.next())     {
    System.out.println("631 Test Marker GHarm 4");
    // get next radio
    radioTemp = rsRadios2.getInt(1);
    // get the TX and RX of the radio
    genericTX = getTX(radioTemp);
    radioTempCon = getConnection(radioTemp);
    genericRX = getTX(radioTempCon);
    // calculate bounds for harmonics test
    txLo = ((txFreq * 2) - genericTX) - 4;     // 4Mhz below TX harmonics check
    txHi = ((txFreq * 2) - genericTX) + 4;     // 4Mhz above TX harmonics check
    rxHi = ((rxFreq * 2) - genericRX) + 4;     // 4Mhz above RX harmonics check
    rxLo = ((rxFreq * 2) - genericRX) - 4;     // 4Mhz below RX harmonics check
    // checks TX and RX of foreign radio against TX, RX of current radio for separation
    if ((txLo > genericTX && txHi < genericTX) || (rxLo > genericRX && rxHi < genericRX))     {
    tstResonanceG = false;     
    break;
    } //end if
    else {
    tstResonanceG = true;
    }     // end else
    } //end foreign radio loop
    // breaking out of loops for return
    if (tstResonanceG == false)
    break;
    }     // end radio loop
    rsRadios2.close();
    rsRadiosTemp.close();
    }     // end sameradio check
    }     // end distance check
    }// end node loop
    rsNode2.close();
    }     // end try
    // Catch statement to stop from crashing in the
    // event of an error during SQL statements.
    catch (java.sql.SQLException resonanceGlobalException) {
    // Prints out the error message produced
    System.out.println(resonanceGlobalException);
    }     // end catch
    // returns result
    return tstResonanceG;
    } //end checkHarmonicResonanceGlobal()
    My apologies if it is a little hard to read, but the indenting is accurate. The Entry Broker methods which this method uses are here:
    public ResultSet getNodes (int projectNo) {
    // creating SQL statement
    sqlStatement = "SELECT nodeNo from tblNode WHERE projectNo = " + projectNo;
    System.out.println(sqlStatement);
    // executing SQL statement
    rsNodes = db.runQuery(sqlStatement);
    // returns ResultSet
    return rsNodes;
    }     // end getNodes
    // Method to get the distance between any two nodes
    public int getDistance (int projectNo, int node, int tempNode)     {
    ResultSet rsX1;                         // Used for obtaining the X-coord of node 1
    ResultSet rsX2;                         // Used for obtaining the X-coord of node 2
    ResultSet rsY1;                         // Used for obtaining the Y-coord of node 1
    ResultSet rsY2;                         // Used for obtaining the Y-coord of node 2
    double distance = 0;                    // Used in Global checks
    int dist = 0;                              // Used in Global checks
    int x1 = 0;                                   // Used in calculating distance
    int x2 = 0;                                   // Used in calculating distance
    int y1 = 0;                                   // Used in calculating distance
    int y2 = 0;                                   // Used in calculating distance
    int xDist = 0;                              // Used in calculating distance
    int yDist = 0;                              // Used in calculating distance
    int distint = 0;                         // Used to store converted values
    try {
    // get the X and Y co-ordinates of both nodes
    sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
    rsX1 = db.runQuery(sqlStatement);
    rsX1.next();
    x1 = rsX1.getInt(1);
    sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + node + " AND projectNo = " + projectNo;
    rsY1 = db.runQuery(sqlStatement);
    rsY1.next();
    y1 = rsY1.getInt(1);
    sqlStatement = "SELECT xCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
    rsX2 = db.runQuery(sqlStatement);
    rsX2.next();
    x2 = rsX2.getInt(1);
    sqlStatement = "SELECT yCoord FROM tblNode WHERE nodeNo = " + tempNode + " AND projectNo = " + projectNo;
    rsY2 = db.runQuery(sqlStatement);
    rsY2.next();
    y2 = rsY2.getInt(1);
    }     // end try
    catch (java.sql.SQLException getDistanceException) {
    System.out.println(getDistanceException);
    // calculating distance
    yDist = y2 - y1;
    xDist = x2 - x1;
    // perform pythagoras theorem for distance
    dist = (xDist * xDist) + (yDist * yDist);
    distance = java.lang.Math.sqrt(dist);
    Double roundFreqTemp = new Double(freqTemp);
    distint = roundFreqTemp.intValue() ;
    return distint;
    } // end get distance method
    // Method to get all the radios in a node
    public ResultSet getRadios(int node)     {
    ResultSet rsRadios;          // Used for obtaining radios in a node
    // creating sql Statement
    sqlStatement = "SELECT * FROM tblRadio WHERE nodeNo =" + node;
    System.out.println(sqlStatement);
    // executing sql Statement
    rsRadios = db.runQuery(sqlStatement);
    System.out.println("EB Test Marker 1: Line 261");
    // returning radio no
    return rsRadios;
    }//end getRadio
    public double getTX(int radioTemp){
    double txTemp = 0;     // Used for storing TX of a radio
    int freqNoTemp = 0; // Used for storing the frequency ID
    rsDummy = getDummy(projectNo);
    // creating SQL statement
    sqlStatement ="Select frequencyNo from tblRadio where radioNo = " + radioTemp;
    System.out.println(sqlStatement);
    // executing SQL statement
    rsTX = db.runQuery(sqlStatement);
    try {
    System.out.println("Test Marker EB1: 317");
    try {
    rsDummy.next();
    }     // end try
    catch     (java.sql.SQLException dummyException)     {
    System.out.println("dummyException" + dummyException);
    }     // end catch
    System.out.println("Test MarkerEB2: 330");
    // moving to first position in rs
    rsTX.next();
    System.out.println("Test MarkerEB3: 334");
    // obtaining data from rs
    freqNoTemp = rsTX.getInt(1);
    System.out.println("Test MarkerEB4: 337");
    rsTX.close();
    }     // end try
    catch (java.sql.SQLException rsTXException)     {
    System.out.println("rsTXExeption: " + rsTXException);
    }     // emd catch
    System.out.println("Frequency No is: " + freqNoTemp);
    rsDummy = getDummy(projectNo);
    sqlStatement = "Select frequency from tblFreq where frequencyNo = " + freqNoTemp;
    System.out.println(sqlStatement);
    rsRX = db.runQuery(sqlStatement);
    try {
    try {
    System.out.println("Test MarkerEB6: 361");
    rsDummy.next();
    }     // end try
    catch     (java.sql.SQLException dummyException)     {
    System.out.println("dummyException" + dummyException);
    }     // end catch
    System.out.println("Test MarkerEB5: 373");
    rsRX.next();
    System.out.println("Test MarkerEB7: 376");
    txTemp = rsRX.getDouble(1);
    System.out.println("Test MarkerEB8: 379");
    rsRX.close();
    }     // end try
    catch (java.sql.SQLException rxException) {
    System.out.println("rxException " + rxException);
    } // end catch
         System.out.println("393 Before return");
    return txTemp;
    }     //end getTX
    public int getConnection(int radio) {
    int nodeCon = 0;                    // Used to return the connected node no
    ResultSet rsConnection;          // Used for obtaining the foreign radio
    // creating SQL statement
    sqlStatement = "SELECT radioNo FROM tblRadio where recRadio = " + radio;
    System.out.println(sqlStatement);
    // executing SQL statement
    rsConnection = db.runQuery(sqlStatement);
    try {
    // moving to first position in rs
    rsConnection.next();
    // obtaining data from rs
    nodeCon = rsConnection.getInt(1);
    }     // end try
    catch (java.sql.SQLException getConnectionException) {
    System.out.println("getConnectionException : " + getConnectionException);
    }     // end catch
    // returns node no.
    return nodeCon;
    And finally, the dummy rs:
    // Dummy method to fix resultSet closed error
    public ResultSet getDummy (int projectNo) {
    sqlStatement = "Select projectName from tblProject where projectNo = " + projectNo;
    System.out.println(sqlStatement);
    rsDummy = db.runQuery(sqlStatement);
    return rsDummy;
    Here is some sample output that we have:
    ----jGRASP exec: java MainGui
    slider value constructor: 50
    116: if(singleton==null) {
    120: singleton=new Resolvotron
    Connection to D/Base establised
    Select projectName from tblProject where projectNo = 3
    Init OK. Beginning solve process
    main OK: beginning frequency assign process
    SELECT nodeNo from tblNode WHERE projectNo = 3
    267: Node number = 2
    SELECT * FROM tblRadio WHERE nodeNo =2
    EB Test Marker 1: Line 261
    Test Marker 1: Line 289
    298: Radio number = 4
    Test Marker 5: Line 308
    Test Marker 3: Line 313
    SELECT frequency from tblFreq WHERE projectNo = 3
    125.5
    Beginning test process
    Test Marker 4: Line 386
    Beginning check 257072
    Test Marker 6: Line 774
    70 Mhz Margin = false
    Beginning local 10Mhz separation check
    SELECT * FROM tblRadio WHERE nodeNo =2
    EB Test Marker 1: Line 261
    Getting TX of radio: 4
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 4
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB5: 373
    Test MarkerEB7: 376
    Test MarkerEB8: 379
    393 Before return
    432: getting connection
    SELECT radioNo FROM tblRadio where recRadio = 4
    438: getting TX of radio: 6
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 6
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB5: 373
    Test MarkerEB7: 376
    Test MarkerEB8: 379
    393 Before return
    java.sql.SQLException: ResultSet is closed
    10 Mhz Local = true
    Beginning 10 Mhz separation check
    SELECT nodeNo from tblNode WHERE projectNo = 3
    Node number is 2
    10 Mhz Global = false
    Beginning local harmonic resonance check
    SELECT * FROM tblRadio WHERE nodeNo =2
    EB Test Marker 1: Line 261
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 4
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB5: 373
    Test MarkerEB7: 376
    Test MarkerEB8: 379
    393 Before return
    SELECT radioNo FROM tblRadio where recRadio = 4
    Select projectName from tblProject where projectNo = 3
    Select frequencyNo from tblRadio where radioNo = 6
    Test Marker EB1: 317
    dummyExceptionjava.sql.SQLException: ResultSet is closed
    Test MarkerEB2: 330
    Test MarkerEB3: 334
    Test MarkerEB4: 337
    Frequency No is: 2
    Select projectName from tblProject where projectNo = 3
    Select frequency from tblFreq where frequencyNo = 2
    Test MarkerEB6: 361
    I'll leave it at that, since the program goes into an endless loop. The dummy Exceptions are our dummy resultsets crashing so the rest can survive. The other stuff is from different methods. You should be able to locate the logic of the program by following the System.outs
    Test Markers with EB refer to the Entry Broker.
    Any help would be appreciated since we cannot find any other way of running this class successfully.
    Steve

    Ok problem solved...
    Basically I was calling one ResultSet after another. Thanks to the Database Broker's structure, this was killing the first ResultSet. I fixed up the loops so that ResultSets were only ever called just before they were needed, and it fixed the problem. The only other errors were simple logic faults which I drummed out in short order. Thanks for the help everyone!

  • Two resultset objects

    IS it possible to define two resultset objects with two different queries inside the same DB class?java.sql.SQLException: Invalid state, the ResultSet object is closed.
         at net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:299)
         at net.sourceforge.jtds.jdbc.MSCursorResultSet.next(MSCursorResultSet.java:1123)
         at DB5.getDetails(Daily_Quote_Response_report.java:238)
         at Daily_Quote_Response_report.main(Daily_Quote_Response_report.java:74)
    java.util.List items = null;
            String query;
            String query2;
            try {
                query =
                       "select * from oqrep_except_resp_summary";
                query2 = "select * from oqrep_except_resp_detail";
                Statement state = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                ResultSet rs = state.executeQuery(query);
                ResultSet rs2 = state.executeQuery(query2);
              //cannot create two rs objects // ResultSet rs2 = state.executeQuery(query);
                items = new ArrayList();Edited by: bobz on 03-Dec-2009 11:16
    Edited by: bobz on 03-Dec-2009 11:16

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.

Maybe you are looking for

  • How to deploy a Web Application in Apache Tomcat?

    Hi, I am a SAP Master Data management guy. But I have been assigned some Java J2EE work. I need help. I want to deploy a JSP Page in Apache Tomcat 5.5.26 Server. The procedure I followed is: I wrote a JSP : helloworld.jsp : <html> <title> Test JSP </

  • Error: Not possible to post down payment clearing.There are no down payment

    Hi expert, I am running a settlement for an internal order and encounter the following error message. "Not possible to post down payment clearing. There are no down payments." Message no. AA571 When checked on the vendor, the invoice has been cleared

  • Nw2004s Authorization display access

    Dear Gurus, I have a problem in an authorization variable for query with cost center infoobect and while executing query it keeps on saying generated statement too long.. thanks

  • Process chain and Abap

    I have an ABAP Report which does following: 1. Create Selection via parameters - in table lt_sel. 2. Delete CUBE 3. Own implemantation using lt_sel and fill cube. 4. Compress Cube. Now point 2. and 4. should work in a process chain. How can i deliver

  • Dropbox and systemd issues...

    Hello! I've installed Dropbox from the AUR, and am starting it for my user using sytemd (sytemctl enable [email protected]). It works fine, but it seems that the actual dropboxd executable only executes a "local one" from my home directory (