HELP! How te retrieve the last row in MYSQL database using Servlet!

Hi ,
I am new servlets. I am trying to retireve the last row id inserted using the servlet.
Could someone show me a working sample code on how to retrieve the last record inserted?
Thanks
MY CODE
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class demo_gr extends HttpServlet {
//***** Servlet access to data base
public void doPost (HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException
     String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
          String param1 = req.getParameter("param1");
          PrintWriter out = resp.getWriter();
          resp.setContentType("text/html");
          String semail, sfname, slname, rfname, rlname, remail, message;
          int cardType;
          sfname = req.getParameter("sfname");
          slname = req.getParameter("slname");
          rfname = req.getParameter("rfname");
          rlname = req.getParameter("rlname");
          semail = req.getParameter("semail");
          remail = req.getParameter("remail");
          message = req.getParameter("message");
          //cardType = req.getParameter("cardType");
          cardType = Integer.parseInt(req.getParameter("cardType"));
          out.println(" param1 " + param1 + "\n");
     String query = "SELECT * FROM greeting_db "
+ "WHERE id =" + param1 + "";
          String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
          query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
          //out.println(" query2 " + query2 + "\n");
          if (semail.equals("") || sfname.equals("") ||
          slname.equals("") || rfname.equals("") ||
          rlname.equals("") || remail.equals("") ||
          message.equals(""))
                    out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
                    out.close();
                    return;
          String title = "Your Card Has Been Sent";
          out.println("<BODY>\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" );
               out.println("\n" +
"\n" +
" From  " + sfname + ", " + slname + "\n <br> To  "
                                        + rfname + ", " + rlname + "\n <br>Receiver Email  " + remail + "\n<br> Your Message "
                                        + message + "\n<br> <br> :");
               if (cardType ==1)
                    out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
               else if(cardType ==2) {
                    out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
               else if(cardType ==3) {
                    out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
else if(cardType ==4) {
                    out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
else if(cardType ==5) {
                    out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
else if(cardType ==6) {
                    out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
out.println("</BODY></HTML>");
     try {
          Class.forName ("com.mysql.jdbc.Driver");
          Connection con = DriverManager.getConnection
          ( url, "*****", "******" );
Statement stmt = con.createStatement ();
               stmt.execute (query2);
               //String query3 = "SELECT LAST_INSERT_ID()";
               //ResultSet rs = stmt.executeQuery (query3);
               //int questionID = rs.getInt(1);
               System.out.println("Total rows:"+questionID);
stmt.close();
con.close();
} // end try
catch (SQLException ex) {
          //PrintWriter out = resp.getWriter();
     resp.setContentType("text/html");
          while (ex != null) { 
     out.println ("SQL Exception: " + ex.getMessage ());
     ex = ex.getNextException ();
} // end while
} // end catch SQLException
catch (java.lang.Exception ex) {
     //PrintWriter out = resp.getWriter();
          resp.setContentType("text/html");     
          out.println ("Exception: " + ex.getMessage ());
} // end doGet
private void printResultSet ( HttpServletResponse resp, ResultSet rs )
throws SQLException {
try {
          PrintWriter out = resp.getWriter();
     out.println("<html>");
     out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
     out.println("<body>");
     out.println("<center><font color=AA0000>");
     out.println("<table border='1'>");
     int numCols = rs.getMetaData().getColumnCount ();
while ( rs.next() ) {
          out.println("<tr>");
     for (int i=1; i<=numCols; i++) {
out.print("<td>" + rs.getString(i) + "</td>" );
} // end for
out.println("</tr>");
} // end while
     out.println("</table>");
     out.println("</font></center>");
     out.println("</body>");
     out.println("</html>");
     out.close();
     } // end try
catch ( IOException except) {
} // end catch
} // end returnHTML
} // end jbsJDBCServlet

I dont know what table names and fields you have but
say you have a table called XYZ which has a primary
key field called keyID.
So in order to get the last row inserted, you could
do something like
Select *
from XYZ
where keyID = (Select MAX(keyID) from XYZ);
Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
This works fine if the emp_id is incremental and of type integer
Query:
select      *
from      employee e,  (select max(emp_id) as emp_id from employee) z
where      e.emp_id = z.emp_id
or
select top 1 * from employee order by emp_id descUday

Similar Messages

  • 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

  • How to retrieve the Last sequence value of a sequence ?

    Can anybody help me out regarding how to retrieve the last executed number or value of a sequence ? As dba_sequence.last_number does not show the original picture of that last value ?

    Rajesh Lathwal wrote:
    Last Number Selected From Sequence :
    SELECT sequence_name, last_number
    FROM user_sequences;That's wrong, this is taking the CACHE in account :
    SQL> create sequence seq ;
    Sequence created.
    SQL> select seq.nextval from dual;
       NEXTVAL
             1
    SQL> SELECT sequence_name, last_number
      2  FROM user_sequences where sequence_name='SEQ';
    SEQUENCE_NAME                  LAST_NUMBER
    SEQ                                     21
    SQL> select seq.currval from dual;
       CURRVAL
             1
    SQL>Nicolas.

  • How to retrieve the last 5 accessed record ??

    How to retrieve the last 5 accessed record ??
    I am using a field for storing the accessed time.
    Pls help with regard to this.
    Thanks in Advance.
    JG

    Depending on your used databasee version, there are several options available, here are just a few examples:
    Sorted Inline-Views & rownum:
    SELECT *
      FROM (SELECT *
              FROM user_objects
             ORDER BY timestamp desc)
    WHERE ROWNUM <= 5;        
    ;Inline-View with analytic function:
    SELECT *
      FROM (SELECT uo.*, ROW_NUMBER() OVER (ORDER BY timestamp desc) rn
              FROM user_objects uo
    WHERE rn <= 5;        
    ;C.

  • How to retrieve the multiple rows data on PDF form in a web service method using WSDL DataConnection

    How to retrieve the multiple rows data on PDF form in a web service method using WSDL DataConnection.
    I have a multiple rows on PDF form. All rows have 4 textfields. I want to submit the multiple rows data to a method defiened in webservice.
    Unable to retrieve the data in multiple rows within webservice method.

    Hi Paul,
    I'm now able to save the retrieved xml in a hidden text field and create dynamic table, and I'm able to fill this table from the XML, but the problem is that I could not find the correct way to loop on the xml, what I'm trying to say, the table will have number of rows with the data of the first row only, so can you tell me the right way to loop on the xml!
    this is my code
    TextField1.rawValue=xmlData.document.rawValue;
    xfa.datasets.data.loadXML(TextField1.rawValue, true, false);
    for(var i=0; i<count; i++)
    xfa.form.resolveNode("form1.P1.Table1.Row1["+i+"].Num").rawValue = xfa.datasets.data.record.num.value;
    xfa.form.resolveNode("form1.P1.Table1.Row1["+i+"].Name").rawValue = xfa.datasets.data.record.name.value;
    Table1.Row1.instanceManager.addInstance(true);
    Thanks
    Hussam

  • How to update transaction data automatically into MySQL database using PI

    Dear All,
    With reference to subject matter I want a sincere advice regarding how to update transaction data automatically into MySQL database using PI. Is there any link available where I can get step-by-step process.
    Ex: I have a MYSQL database in my organization. Whenever a delivery created in SAP some fields like DO Number, DO quantity, SO/STO number should get updated in MYSQL database automatically.
    This scenario is related to updation of transactional data into MYSQL DB and I want your suggestions pertaining to same issue.
    Thanks and Regards,
    Chandra Sekhar

    Hi .
    Develop a sceanrio between SAP to Database system,When the data updates in SAP Tables read the data and update it in DATA Base using JDBC adapter,but there will be some delay in updating data in MySQL.
    serach in sdn for IDOC-TOJDBC sceannario,many documents available for the same.
    Regards,
    Raja Sekhar

  • How to retrieve the last inserted row

    This may be a question with a very known answer but I couldn't find any within this forum.
    What is the proper way to retrieve the just inserted record ?
    I'm accessing the DB from external Java and at this moment I use a timestamp column in order to retrieve the inserted row. So I generate an unique timestamp ('20020615184524356') which I inserted during the insert operation. I retrieve the just inserted row using "select * from fooTable where(timestamp='20020615184524356')".
    Is this the general idea or am I totally wrong ?

    hi Shaik Khaleel,
    Just wanted to clarify my doubts regarding rowid.
    Please refer the subject as "abt rowid" in previous posting and ur reply for that was
    "its an unique number throughout the database, its an hexadecimal number. it assigns the rowid of the deleted row in future , but not to the immediate insertation row."
    As u have mentioned the rowid of the deleted row can be assigned to a new row in future,
    wont the following query fail.
    select * from temp where rowid=(select max(rowid) from temp); -- in oracle. ~chandru

  • 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!

  • How to display the last row in a table

    I have a table that is constantly updating, and I always want to see the last row. How can I get my table to auto scroll?

    Hi žabić,
    there is a property called "top left visible row". You can use it to scroll your table.
    edit:
    Maybe this is not the exact name, but you can see an example here
    Mike
    Message Edited by MikeS81 on 05-27-2010 03:57 PM

  • How to Finding the Last Row Value in Datagrid?

    Hi Everyone,
    Thanks in Advance.
    I need your help, to find the last row data in Datagrid.
    Actually i am using Datagrid to display my Data in flex. In my data i stored the gender value of employees. So if the last row in my datagrid is "female" i need to be highlight that particular row. So please help me to solve this issue.
    Thanks,
    Charles. J

    datagrid.selectedIndex = datagrid.dataprovider.length;
    ^ something like this will select the last row in the datagrid.
    if you need to check it's value, you might need to cast an object here, based on the index value, and check it's gender value.
    datagrid.selectedIndex = datagrid.dataprovider.length;
    if (datagrid.selectedItem["gender"] == "female") {
    //handle here

  • 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

  • How to retrieve the data from SAP-BAPI by using VB Code

    Hi ,
    I am new to BAPI.
    V have created an application in Visual Basic with the following fields
    EmpNo , EmpName, Addr1, Addr2, City and Phone (Only for Test)
    We have written the code for SAVING the data into SAP. Already we have
    constructed a table with the respective fields in SAP.
    For that we ourself created our own BAPI Structure / Function Group /
    Function Module/ Business Object - RELEASED related elements.
    1)Established the connection successfully.
    2)Stored the data into SAP Successfully and v r in need of
    3)HOW TO RETRIEVE THE DATA FROM SAP (USING GETLIST.....GETDETAIL....)
    Following is the code :
    'BAPI Structure  : ZBAPIEMP
    'Function Group  : ZBAPIEMP
    'Function Module : ZBAPI_EMP_CREATEFROMDATA
    'Business Object : ZBAPIEMP
    'Function Module : ZBAPI_EMP_GETLIST
    Dim bapictrl As Object
    Dim oconnection As Object
    Dim boEmp As Object
    Dim oZEmp_Header As Object
    Dim oImpStruct As Object
    Dim oExpStruct As Object
    Dim oreturn As Object
    Dim x As String
    Private Sub Form_Load()
    Set bapictrl = CreateObject("SAP.BAPI.1")
    Set oconnection = bapictrl.Connection
    oconnection.logon
    Set boEmp = bapictrl.GetSAPObject("ZBAPIEMP")
    Set oZEmp_Header = bapictrl.DimAs(boEmp, "CreateFromData", "EmployeeHeader")
    Set oImpStruct = bapictrl.DimAs(boEmp, "GetList", "EmployeeDispStruct")
    End Sub
    Private Sub cmdSave_Click()
        oZEmp_Header.Value("EMPNO") = txtEmpNo.Text
        oZEmp_Header.Value("EMPNAME") = txtEmpName.Text
        oZEmp_Header.Value("ADDR1") = txtAddr1.Text
        oZEmp_Header.Value("ADDR2") = txtAddr2.Text
        oZEmp_Header.Value("CITY") = txtCity.Text
        oZEmp_Header.Value("PHONE") = txtPhone.Text
        boEmp.CreateFromData EmployeeHeader:=oZEmp_Header, Return:=oreturn
        x = oreturn.Value("Message")
        If x = "" Then
            MsgBox "Transaction Completed!..."
        Else
            MsgBox x
        End If
    End Sub
    Private Sub cmdView_Click()
    End Sub
    COULD ANYBODY GUIDE ME, HOW TO RETRIEVE THE DATA FROM BAPI, FOR THE WRITTEN CODE.

    I didn't seen any other answers but here's how it's been done previously in our organization for a custom BAPI. In this example, we give material and language to return the part description. It's not specific to your project but may give you ideas..
    -Tim
    Option Compare Database
    Dim SAPLOGIN As Boolean
    Dim FunctionCtrl As Object
    Dim SapConnection As Object
    Sub SAPLOGOUT()
    On Error GoTo LogoutFehler
        SapConnection.logoff
        SAPLOGIN = False
    Exit Sub
    LogoutFehler:
        If Err.Number = 91 Then
            Exit Sub
        Else
            MsgBox Err.Description, vbCritical, "Fehler-Nr." & CStr(Err.Number) & " bei SAP-Logout"
        End If
    End Sub
    Function SAPLOG() As Boolean
    'Verbindungsobjekt setzen (Property von FunctionCtrl)
       Set FunctionCtrl = CreateObject("SAP.Functions")
       Set SapConnection = FunctionCtrl.Connection
    'Logon mit Initialwerten
       SapConnection.Client = "010"
       SapConnection.Language = "EN"
       SapConnection.System = "PR1"
       SapConnection.SystemNumber = "00"
       'SapConnection.Password = ""
       SapConnection.GroupName = "PR1"
       SapConnection.HostName = "168.9.25.120"
       SapConnection.MessageServer = "168.9.25.120"
         If SapConnection.Logon(0, False) <> True Then  'Logon mit Dialog
             Set SapConnection = Nothing
             DoCmd.Hourglass False
             MsgBox "No connection to SAP R/3 !"
             SAPLOGIN = False
             SAPLOG = False
             Exit Function
          End If
        SAPLOG = True
    End Function
    Function MatDescr(MatNr As String)
    Dim func1 As Object
    Dim row As Object, X As Integer, ErsteNr As String
    Dim DatensatzZähler As Long
    Dim RowField(1 To 50, 0 To 1) As String, RowLine As Long
        If Not SAPLOGIN Then
            If Not SAPLOG() Then
                MsgBox "No connection  to SAP !", 16
                SAPLOGOUT
                Exit Function
            End If
        End If
    ' Instanziieren des Function-Objektes
    Set func1 = FunctionCtrl.Add("Z_BAPI_READ_MAKT")
    ' Export-Paramter definieren
    func1.exports("MATNR") = MatNr
    func1.exports("SPRAS") = "EN"
    DoEvents
    If Not func1.call Then
        If func1.exception <> "" Then
            MsgBox "Communication Error with RFC " & func1.exception
        End If
        DoCmd.Hourglass False
        SAPLOGOUT
        Exit Function
    Else
      MatDescr = func1.imports("MAKTX")
    End If
    If MatDescr = "" Then
        MatDescr = "PART NO. NOT FOUND"
    End If
    End Function

  • How to get the field row name of database from a form?

    Hello experts,
    I am newer in OIM and developments with the API's.
    I have this environment,
    one resource that have the attribute department
    relationship with the database row
    UD_RESOURCE1_DEPARTMENT and other resource with the same attribute in, UD_RESOURCE2_DEPARTMENT
    I am programing one java class that put values in the
    form field through the table name, sample,
    UD_RESOURCE_DEPARTMENT.
    I let some code:
    # Hash table with the value of Department
    myMap.put("UD_RESOURCE_DEPARTMENT", value);
    # and save in the resource form
    tcFormInstanceOperationsIntf tcform = (tcFormInstanceOperationsIntf)tcUtilityFactory.getUtility(dataProvider,"Thor.API.Operations.tcFormInstanceOperationsIntf");
    tcform.setProcessFormData(Long.parseLong(formKey), myMap);
    But this solution implies know the name of the field in the database and not is a global solution.
    I am interesting in know how I can obtain the name of the
    row field of the database for the atribute. Does anybody know how to obtain the row field name of database from an IT Resource or through the field name of the form?
    Is this the correct way to store data in a form?
    Thanks in advanced.

    Hi,
    Thank you.
    I have seen this function in the OTN help, but how can i get the index number. My requirment is when saving the data, I need to save both the value and the element name into the database,
    Also it is tabular block, more than one rows
    Thanks again

  • How to retrieve the data from MDM hierarchy table using MDM Java API

    Hi,
    I had a hierarchy table in MDM. This table had some column say x. I want to retrieve the values of this x column and need to show them in a drop down using MDM Java API.
    Can anyone help me to solve this?
    Regards
    Vallabhaneni

    Hi,
    Here is your code...
    TableId Hier_TId = repository_schema.getTableId(<hierarchy table id>);
    java.util.List list = new ArrayList();
    ResultDefinition Supporting_result_dfn = null;
    FieldProperties[] Hier_Field_props =rep_schema.getTableSchema(Hier_TId).getFields();
    LookupFieldProperties lookup_field = null;
    TableSchema lookupTableSchema = null;
    FieldId[] lookupFieldIDs = null;
    for (int i = 0, j = Hier_Field_props.length; i < j; i++) {
    if (Hier_Field_props<i>.isLookup()) {     
                                  lookup_field = (LookupFieldProperties) Hier_Field_props<i>;
         lookupTableSchema =repository_schema.getTableSchema(lookup_field.getLookupTableId());
                                  lookupFieldIDs = lookupTableSchema.getFieldIds();
         Supporting_result_dfn = new ResultDefinition(lookup_field.getLookupTableId());
         Supporting_result_dfn.setSelectFields(lookupFieldIDs);
         list.add(Supporting_result_dfn);
    com.sap.mdm.search.Search hier_search =new com.sap.mdm.search.Search(Hier_TId);
    ResultDefinition Hier_Resultdfn =     new ResultDefinition(Hier_TId);
    Hier_Resultdfn.setSelectFields(rep_schema.getTableSchema(Hier_TId).getDisplayFieldIds());
    ResultDefinition[] supportingResultDefinitions =
    (ResultDefinition[])list.toArray(new ResultDefinition [ list.size() ]);
    RetrieveLimitedHierTreeCommand retrieve_Hier_tree_cmd =
    new RetrieveLimitedHierTreeCommand(conn_acc);
    retrieve_Hier_tree_cmd.setResultDefinition(Hier_Resultdfn);
    retrieve_Hier_tree_cmd.setSession(Auth_User_session_cmd.getSession());
    retrieve_Hier_tree_cmd.setSearch(hier_search);
    retrieve_Hier_tree_cmd.setSupportingResultDefinitions(supportingResultDefinitions);
    try {
         retrieve_Hier_tree_cmd.execute();
    } catch (CommandException e5) {
              // TODO Auto-generated catch block
              e5.printStackTrace();
    HierNode Hier_Node = retrieve_Hier_tree_cmd.getTree();
    print(Hier_Node,1);
    //method print()
    static private void print(HierNode node, int level) {
    if (!node.isRoot()) {
         for (int i = 0, j = level; i < j; i++) {
              System.out.print("\t");
         System.out.println(node.getDisplayValue());
    HierNode[] children = node.getChildren();
    if (children != null) {
              level++;
    for (int i = 0, j = children.length; i < j; i++) {
    print(children<i>, level);
    //end method print()
    Best regards,
    Arun prabhu S
    Edited by: Arun Prabhu Sivakumar on Jul 7, 2008 12:19 PM

  • How to know the last time a table was used?

    I was trying to find a log or something that can tell me when and who was the last one/s that used a table.
    Could someone help me?
    thanks

    How can I activate the auditing? http://download-east.oracle.com/docs/cd/B19306_01/network.102/b14266/auditing.htm#i1011984
    Daljit Singh

Maybe you are looking for

  • O2 and second rate service with a rubbish phone

    I went to Apple and iphone in preference to Blackberry. What a mistake. For three months I must have spent fifty hours on the phone to O2 with a problem they cannot remedy and they say Apple cannot remedy. Are they thick. I have even given them my ac

  • Please help, someone please, this is a big issue

    2nd g-thouch owner................. ok, well I have been downlowding my songs, right, for about a week now. But i dont use itunes to get my songs,I use MP3 Rocket to get all my songs and then I put the songs that i got onto the itunes. well I did tha

  • Outlook connector crashes with Office 2007 SP2

    Hello. Microsoft has started pushing out Office 2007 SP2, resulting in Outlook crashes for Connector users who apply the patch. The only workaround we've found is to restore the users's system with Windows Restore, and then hide SP2 with Windows Upda

  • How can I convert a Numbers '08 spreadsheet to Numbers 3.0 without purchasing Numbers '09?

    I have a spreadsheet that I created in '08 when I purchased my first Macbook Pro.  I'm a truck driver and through the forum, individuals help me create a spreadsheet that I use for calculating pay.  My previous MB is down and out.  Just had barely en

  • API to update/ create Organization EIT

    Hi All, I 'am trying to find the API to update/ create EITs for HR Organizations. While I can find the API to update person and assignments hr_assignment_extra_info_api/ hr_person_extra_info_api, I 'am not able to find out the API/ package for Organi