Trying to get the last row from a resultset

Hi,
I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
I've tried a variety of things and most seem to return the first row, not showing the updated values.
Or, if it does work, it takes to long to load, and i get an error.
here is the working code;
Object m = machCBX.getSelectedItem():
try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE,  //tried both INSENSITIVE and SENSITIVE
ResultSet.CONCUR_READ_ONLY);
last.setString(1, String.valueOf(m));
rs. = last.executeQuery();
if(rs.isAfterLast) == false ) {
rs.afterLast();
while(rs.previous()) {
String p = rs.getString("part");
int c = rs.getInt("count");
partJTX.setText(p);
countJTX.setText(c);
}this grabs values, but they are not the last entered values.
Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
thanks
-PD

OK, you've got a major misunderstanding...
The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course).

Similar Messages

  • How to get the last row in a resultset or query

    Hi All
    Say If I have a complex query which returns a resultset say 15 rows. Now I want to limit the output showing only the last row.
    How can we do this

    Keep in mind Oracle does not keep "row" order as such. Unlike a graphical type db like Access, Oracle will not always give you back the results in order.
    Even if you were to use a sequence, your query is never guaranteed to give back the results in the order you are expecting. You must then give an order by statement to all queries expecting the order.
    Your definition of last row too is vague - if it is in fact the greatest amount, use the inline view suggestion. If you simply want to see the last inserted row, consider adding a last_update_date column inserting the sysdate (by a trigger perhaps). This would then allow you to see the last inserted row.
    Enjoy!

  • Getting the first row from a ResultSet??

    I have a query that returns a set of values but am interested only in the first value.How can I get that. I tried to use getArray method but that gives a "java.sql.SQLException: Exhausted Resultset".
    Any suggestions??

    I think I'm having the same problem with you.
    this is my method:
    private Vector getData( ResultSet rs){
    String str = "";
    try{
    while( rs.next() ){
    str = rs.getString( 1 );
    rows.addElement( str );
    }catch( SQLException sqlex ){
    sqlex.printStackTrace();
    return rows;
    I don' t know if you meant this.hoping this can help you

  • Cant get the last row in jtable

    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
            //creating the table
        for (i=0;i<this.rows;i++)
         model.insertRow(i,new Object[]{"input Y1:",""});
                for ( i=i;i<this.Amount+this.rows;i++)
         model.insertRow(i,new Object[]{"input Amount:",""});
    //end of creatingthis code creats the table that i need and its works right.
    for(i=0;i<rows;i++){
                  fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
            int j=0;
            String s=GetData(table, 1, 4).toString();
            //the problem line
            String s1=GetData(table, 1, 5).toString();
        public Object GetData(JTable table, int col_index, int row_index){
        return table.getModel().getValueAt(row_index, col_index);
      }this line i get ""
    String s1=GetData(table, 1, 5).toString();
    Edited by: vitaly87 on 00:41 08/04/2011

    vitaly87 wrote:
    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
    this line i get ""
    String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
    If it hadn't found the row, I expect you would have got an Exception
    Winston

  • HT201328 I am trying to get the unlock code from ATT

       I am trying to get the unlock code from ATT for my Iphone 4S bought in an Apple store, and now they refused to give it, because it is reported as stolen.
    I have all the invoices and recepts, .
    How can I do to unlock the phone if they continue in their negative and hostile attitude???
    Thanks,
    Paul
    [email protected]

        hipichik Hello there. Let's get more specific information. What type of lock code are you referring to? And what are you looking to do with your phone?
    SheritaH_VZW
    Follow us on Twitter
    @VZWSupport

  • Getting the Selected Row from a JTable

    hi,
    how Can i get the Selected row from a JTable
    thanks...

    You know that JTable class? Well, you see those methods in it called "getSelectedRow()" and "getSelectedRows()"...?

  • Read to get the last line from a File

    Hi
    I am sending in a clarification , hoping that I get an efficient solution from the group, should somebody have come across this scenario and implemented.
    How to read or get the last line from a text file , which usually have a no of records, without actually reading or looping through all the lines
    I know there is some solution with the RandomAccessFile, but given there can be some encoding issues or so.
    Please let me know if somebody have implemented the same.
    Thanks n advance

    The character encoding could, indeed, be an issue especially with UTF-8. I think what I'd do is to create a byte array with the encoded, expected end of line sequence in it and work on the file in bytes. For example, seek to the last 100 bytes of the file, read those bytes and look for an EOL sequence backwards. If not found read the previous 100, 200, 400 bytes etc. until you do find an end of line. Then seek to after the EOL and read normally. Remember an EOL sequence might cross a boundary.
    UTF-8 would be a problem, especially with a unix format file because you might mistake part of a multi-byte sequence for '\n'. To be reliable on UTF-8 you'd need to go back three characters looking for sequence start markers (has the previous character got the top bit set, or the one before that the first two bits set, or the one before that the top three bits). Or you could just react to an encoding exception and try another position.

  • How to get the last row of a database table.

    HI ,
    I want to get record exactly from the last row of a database table.
    How is that possible?

    Hi,
    To fetch last record from an internal table, just do find the number of records in it and read using index.
    DESCRIBE TABLE ITAB LINES L_LINES.
    READ TABLE ITAB INDEX L_LINES.
    You can also use LOOP .. ENDLOOP but the above method is better (performance wise).
    using LOOP .. ENDLOOP.
    LOOP AT ITAB.
    **do nothing
    ENDLOOP.
    **process ITAB (Header record of ITAB).
    **after ENLOOP, ITAB will have the last record of the internal table.
    [here ITAB is internal table as well as header record.]
    But what is the requirement?
    If you are looking for the current record of an employee then you can use ENDDA = HIGH_DATE.
    My advice is to review your requirement again and try to fetch only that record which you need.
    Mubeen

  • Get the last query from the current user

    Is there a way to get the last query of the current user, so every query could be log with a database trigger?
    Let's just say I execute:
    DELETE xxxx;
    I tried :
    SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session where audsid=userenv('sessionid'));
    But the result of this query is :
    'SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session where audsid=userenv('sessionid'))'
    Is there a way to execute a query that would return :
    'DELETE xxxx'
    Thanks

    You could join SQL_ADDR in v$session with ADDRESS in v$sqlarea to determine the SID that executed that SQL statement last. Note that PREV_SQL_ADDR in v$session will indicate the previous SQL he executed. Though you would have to look at these tables very often to get all SQL statements issued. One note here, I think if a different user ran the SAME SQL with just bind var differences the SQL_AREA will only show the last user’s information that executed it.
    BTW - it will show deletes also...

  • How can I get the selected rows from two ALV grids at the same time?

    I have a program that uses two ALV grids in one dialog screen. I'm using the OO ALV model (SALV* classes).
    The user can select any number of rows from each grid. Then, when a toolbar pushbutton is pressed, I'd have to retrieve the selected rows from both grids and start some processing with these rows.
    It is no problem to assign event handlers to both grids, and use the CL_SALV_TABLE->GET_SELECTIONS and CL_SALV_SELECTIONS->GET_SELECTED_ROWS methods to find out which rows were marked by the user. Trouble is, this only works when I raise an event in each grid separately, for instance via an own function that I added to the grid's toolbar. So, I can only see the selected rows of the same grid where such an event was raised.
    If I try to do this in the PBO of the dialog screen (that contains the two grids), the result of CL_SALV_SELECTIONS->GET_SELECTED_ROWS will be empty, as the program does not recognize the marked entries in the grids. Also, an event for grid1 does not see the selected rows from grid2 either.
    As it is right now, I can have an own button in both grid's toolbar, select the rows, click on the extra button in each grid (this will tell me what entries were selected per grid). Then, I'd have to click on a third button (the one in the dialog screen's toolbar), and process the selected rows from both grids.
    How can I select the rows, then click on just one button, and process the marked entries from both grids?
    Is it somehow possible to raise an event belonging to each grid programmatically, so that then the corresponding CL_SALV_SELECTIONS->GET_SELECTED_ROWS will work?
    Thanks.

    Hello Tamas ,
    If I try to do this in the PBO of the dialog screen (that contains the two grids), the result of CL_SALV_SELECTIONS->GET_SELECTED_ROWS will be empty, as the program does not recognize the marked entries in the grids. Also, an event for grid1 does not see the selected rows from grid2 either.--->
    is it possible to  have a check box in each grid  & get the selected lines in PAI of the screen ?
    regards
    prabhu

  • I lost all of my Itunes music because of an infection that required them to wipe my computer.  I am trying to get the music back from multiple sources.  What I have recovered is a mess. Albums are mixed or songs not grouped as album. Help?

    My computer got infected with some terrible virus.  I contacted the manufacturer and they said the only thing to do was wipe the whole thing. I could not back it up bec this mess?ause it would include the infection. I have been trying to recover the lost music from several different places.  A friend tried to help me by putting all of his music on my computer from his external hard drive. That was very nice of him but now it is a terrible mess. The recovered songs are not grouped into albums correctly.  Some albums are mixed - every other song is from the other album.  Some songs are listed separately and not grouped as an album.  I tried to ask iTunes to find album art work and it has been running that for over 48 hours. Is that possible?  When I try to stop it I get a message that says I will lose all the data.  I admit that I am not very tech. savvy and I really don't know what I am doing.  It took me more than 20 years to make that collection and I am heart broken. Do you have any ideas about how I start to fix

    Unfortunately you've discovered too late how important it is to maintain an up-to-date backup of your iTunes library (and all other data of value).  You could, before wiping the drive, have considered making use of a commercial data recovery service that could (albeit at considerable cost) have extracted your library from the hard disk, even if virus infected.
    In the absence of that option, you will need to restore the content of your library from its original sources:
    Depending on your location, you may be able to re-download any iTunes Store purchases that are still available on the Store
    Likewise, most digital purchases from Amazon (including auto-rip copies of purchased CDs) should be available from the Amazon Cloud and via the Amazon Music application - the same may be true of other commercial sources for digital downloads
    Content imported from your CDs will have to imported again
    The specific situation that you describe regarding the music imported from your friend's external HDD suggests that either the source is badly organized and/or originates from a source other than iTunes (other media players may use alternative tags for information like artist, title, album, etc. that are not wholly consistent with how iTunes handle these).  Without details of the issues you're seeing it is difficult to suggest a remedy other than going through the media album-by-album, track-by-track, and correcting the inconsistencies.
    In the absence of a backup or access to the original library data there is no option other than painstakingly recreating your library as described above.  As you do so, you'll now realize how important creating and maintaining backups are - in my case I have at all times three separate duplicates of my library, in two different locations, where none is ever more than a week old compared to the content of my master library.

  • How to get the last record from the database

    I am using MS Access database and Swings as GUI. I want to get the last record of a particular column from the table and store it as a varaible.

    Hi
    To get Last record of resultset, you have pass some parameter in constructor of CreateStatement.In such case Resultset should be scrollable and Readonly
    Example
    objStatement=objCon.createStatement ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    mwwResultSet=cwwStatement.executeQuery(mwwSqlQuery);
    while(mwwResultSet.next())
    if(mwwResultSet.isLast())
    //Fetch the required column record.
    String abc=mwwResultSet.getString(1);
    I think this will work. Try it.
    bye

  • Master Child tables how to get the latest rows from both

    Hi,
    Need some help with the sql. I have two tables Master & Child. In my Master table I have multiple rows for the same record and in the child table also multiple rows for the same master row how can I get the latest one's from both.
    For example Data in my Master table looks like
    CONT_ID                  SEQ_NUM        DESCRIPTION
    1                         189             Update 2
    1                         188             Update 1
    1                         187              NewNow in the child table for the same CONT_ID I may have the following rows
    CONT_ID                   UPDATED_DATE                                     STATUS
    1                        3/16/2010 2:19:01.552700 PM                          P
    1                        3/16/2010 12:29:01.552700 PM                         A
    1                        3/16/2010 12:29:01.552700 PM                         P
    1                        3/16/2010 12:19:01.552700 PM                         NIn my final query how can I get the row with seq_num 189 as it's the latest in Master table and from child table the row with status of P as it's the latest one based on the time. Here is the query i have but it returns the latest row from the child table only and basically repeats the master table rows as opposed to one row that is latest from both:
    Thanks

    Hi,
    You can use the analytic ROW_NUMKBER function to find the latest row for each cont_id in each table:
    WITH     got_m_rnum     AS
         SELECT     cont_id,     seq_num,     description
         ,     ROW_NUMBER () OVER ( PARTITION BY  cont_id
                                   ORDER BY          seq_num     DESC
                           ) AS m_rnum
         FROM    master_table
    --     WHERE     ...     -- any filtering goes here
    ,     got_c_rnum     AS
         SELECT     cont_id, updated_date,     status
         ,     ROW_NUMBER () OVER ( PARTITION BY  cont_id
                                   ORDER BY          updated_date     DESC
                           ) AS c_rnum
         FROM    child_table
    --     WHERE     ...     -- any filtering goes here
    SELECT     m.cont_id,     m.seq_num,     m.description
    ,     c.updated_date,     c.status
    FROM     got_m_rnum     m
    JOIN     got_c_rnum     c     ON     m.cont_id     = c.cont_id
                        AND     m.m_rnum     = c.c_rnum
                        AND     m.m_rnum     = 1
    ;If you'd like to post CREATE TABLE and INSERT statements for the sample data, then I could test this.
    If there happens to be a tie for the latest row (say, there are only two rows in the child_table with a certain cont_id, and both have exactly the same updated_date), then this query will arbitrarily choose one of them as the latest.

  • How to get the last row

    I have 10 rows in my table and I have to retrive last row using rownum.
    For this I use
    SELECT * from <table_name>
    where rownum<=10
    minus
    SELECT * from <table_name>
    where rownum<=9
    The result is no rows selected
    In the same case if I use
    SELECT rownum from <table_name>
    Where rownum <= 10
    minus
    SELECT rownum from <table_name>
    where rownum <=9
    The result is 10
    Why this happend.
    If the result is 10, then why the row whose rowid is 10 is not retrived

    All
    Please bear in mind that ROWNUM is an attribute of the query NOT the table. The last row returned by an unORDERed SELECT statement may be the most recently inserted row but is not guaranteed to be so.
    The only way of assuring yourself of returning the most recent row is either to timestamp all your tables with a date_created column or to use a primary key with an ascending value.
    rgds, APC

  • Getting the last action from a managed bean

    Is it possible to get the last action that was submitted from within a backing bean.
    I have an application that has a context specific menu at the top of the page. The context menu is generated using a backing bean which is called from a tiled jsp, called contextmenu.jsp.
    The context menu backing bean needs to know what page it is on so that it can generate the correct menu, so is it possible to get hold of the last action submitted, or the current page from within the backing bean?
    Any help would be much apprecieated.
    Jamie Cash

    Thanks for your help,
    but ...
    We will be developing over 200 jsps and don't want to load the development effort with a backing bean for each jsp.
    The solution that I finally arrived at is using the following code in the menubean to get the view id, and make the decision based on that.
    public NavigationMenuItem[] getContextMenu()
         //Get view id
              String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
              logger.debug("view id: " + viewId);
              //Menu
              NavigationMenuItem[] contextMenu = null;
              if(viewId.equals("/home.jsp"))
                   .... Code to get context menu from Stateless Session bean     
              //Return menu
              return contextMenu;
    Regards
    Jamie

Maybe you are looking for

  • Modify Delivery Date in PO at line item level

    Hi, when we create line items in PO, there is a fiels called dilivery date at line item level. I want it to modify by fetching the value of delivery date from custom table on the basis of some selection criteria during PO creation. Please anyone can

  • Calling a communication channel externally

    Hi Experts I want to dynamically call the communication channel from bpm during runtime.For this i am using a transformation step and writing a java code to call the url.But how to pass the username and password required to login into the adapter fra

  • Remove pushbutton during runtime

    HI experts, how can I remove a pushbutton during runtime from the screen? if certain conditions are true than I have to remove the pushbuttons from displaying.

  • Production Order With out BOM

    Hi Gurus, I have a scenario where I want to produce a Material With out BOM but with a Routing. Here I when I am creating a production order it ask for  Valid BOM, please let me know the setting os that it will not ask for BOM and no error message is

  • Error when sending iCloud mail in Mavericks

    Trying to send an email in Mavericks Mail from iCloud account and got the following error: MCMailErrorDomain error 1032. Does this simply mean that iCloud had a hiccup (there was no outage reported at https://www.apple.com/support/systemstatus/), or