How to get last inserted id from database

Hello,
In PHP Language, mysql_insert_id() gives the last inserted ID without writing any Queries in the code. Is there similar mechanism to do in Jsp page. I need to insert data in one table and in the meantime, with the last inserted ID i need to insert another sort of data in another table.
Can u plz help me out?

You can use Statement#getGeneratedKeys().
The DDL should look like at least (you can use INT UNSIGNED instead, your choice):ID BIGINT AUTO_INCREMENT PRIMARY KEYBasic example:int affectedRows = statement.executeUpdate("INSERT INTO table (column1, column2) VALUES ('value1', 'value2')");
Long insertID = null;
if (affectedRows == 1) {
    ResultSet generatedKeys = statement.getGeneratedKeys();
    if (generatedKeys.next()) {
        insertID = new Long(generatedKeys.getLong(1));
}Using MySQL Connector/J 5.0.

Similar Messages

  • Retrive last inserted  record  from database table

    Hi,
    some body inserting a record into table 'A' through some procedure/java program.i want to retrive the last inserted record from database table.records are not stored in order.Can any body help me.

    In general, unless you are storing a timestamp as part of the row or you have some sort of auditing in place, Oracle has no idea what the "first" or "last" record in a table is. Nor does it track when a row was inserted.
    - If you have the archived logs from the point in time when the row was inserted, you could use LogMiner to find the timestamp
    - If the insert happened recently (i.e. within hours), you may be able to use flashback query to get the value
    - If you're on 10g or later and the table was built with ROWDEPENDENCIES and the insert happened in the last few days and you can deal with a granularity of a few seconds and you don't need 100% accuracy, you could get the ORA_ROWSCN of the row and convert that to a timestamp.
    If this is something you contemplate needing, you need to store the data in the row or set up some sort of auditing.
    Justin

  • How to get data in jtable from database

    i m working on core java application i want to use jtable to show records to user. jtable will get records from mssql database. how to do this.. i m new so plz tell me briefly..with coding...
    thanks

    i have use this link:
    import java.sql.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * This class takes a JDBC ResultSet object and implements the TableModel
    * interface in terms of it so that a Swing JTable component can display the
    * contents of the ResultSet. Note that it requires a scrollable JDBC 2.0
    * ResultSet. Also note that it provides read-only access to the results
    public class ResultSetTableModel implements TableModel {
    ResultSet results; // The ResultSet to interpret
    ResultSetMetaData metadata; // Additional information about the results
    int numcols, numrows; // How many rows and columns in the table
    * This constructor creates a TableModel from a ResultSet. It is package
    * private because it is only intended to be used by
    * ResultSetTableModelFactory, which is what you should use to obtain a
    * ResultSetTableModel
    ResultSetTableModel(ResultSet results) throws SQLException {
         this.results = results; // Save the results
         metadata = results.getMetaData(); // Get metadata on them
         numcols = metadata.getColumnCount(); // How many columns?
         results.last(); // Move to last row
         numrows = results.getRow(); // How many rows?
    * Call this when done with the table model. It closes the ResultSet and
    * the Statement object used to create it.
    public void close() {
         try { results.getStatement().close(); }
         catch(SQLException e) {};
    /** Automatically close when we're garbage collected */
    protected void finalize() { close(); }
    // These two TableModel methods return the size of the table
    public int getColumnCount() { return numcols; }
    public int getRowCount() { return numrows; }
    // This TableModel method returns columns names from the ResultSetMetaData
    public String getColumnName(int column) {
         try {
         return metadata.getColumnLabel(column+1);
         } catch (SQLException e) { return e.toString(); }
    // This TableModel method specifies the data type for each column.
    // We could map SQL types to Java types, but for this example, we'll just
    // convert all the returned data to strings.
    public Class getColumnClass(int column) { return String.class; }
    * This is the key method of TableModel: it returns the value at each cell
    * of the table. We use strings in this case. If anything goes wrong, we
    * return the exception as a string, so it will be displayed in the table.
    * Note that SQL row and column numbers start at 1, but TableModel column
    * numbers start at 0.
    public Object getValueAt(int row, int column) {
         try {
         results.absolute(row+1); // Go to the specified row
         Object o = results.getObject(column+1); // Get value of the column
         if (o == null) return null;
         else return o.toString(); // Convert it to a string
         } catch (SQLException e) { return e.toString(); }
    // Our table isn't editable
    public boolean isCellEditable(int row, int column) { return false; }
    // Since its not editable, we don't need to implement these methods
    public void setValueAt(Object value, int row, int column) {}
    public void addTableModelListener(TableModelListener l) {}
    public void removeTableModelListener(TableModelListener l) {}
    the table is showing column name from database but not showing the data in row now what to do

  • How to get time specification detail from database

    Dear All,
    How can I get the time specification detail from data base?
    Time specification is a 32 bit hexadecimal no type guid_32.
    Function wfd_timespec_reload provide the modified time specification detail.
    FUNCTION wfd_timespecs_reload
    ""Local Interface:
    *"  IMPORTING
    *"     VALUE(I_LOGSYS) TYPE  LOGSYS
    *"     VALUE(I_AWTYP) TYPE  WFD_AWTYP
    *"     VALUE(IT_TIMESPEC_KEYS) TYPE  WFD_KEY_TAB
    *"  EXPORTING
    *"     VALUE(ET_TIMESPEC_DETAILS) TYPE  WFD_TIMESPEC_TAB
    *"     VALUE(ET_INVALID_TIMESPECS) TYPE  WFD_KEY_TAB
    *"     VALUE(ET_CHANGED_TIMESPEC_KEYS) TYPE  WFD_KEY_TAB
    *"     VALUE(ET_RETURN) TYPE  BAPIRET2_T
    This function take time spec from data base not from cache(buffer) so provide the modified time spec in the same session.
    I need any newly created time specification detail also. So I can show all the time spec detail in my function module for any user in the same session.
    Can anyone provide the sample code for it?
    Thanks,
    Anup Garg

    Yes I can see the pattern.
    When I get the set of numbers from database UI doesn't know what is the the list of numbers database has. I need to choose some next available number that is not in database. In the list that u are talking about next available number is 7. Its something similar to when we try to create any mailid, while registration it gives some default id which is not existing which user can choose to create his mailid. How can I get similar feature?

  • How to get the insert scripts from a table data

    hi all,
    i want insert scripts for 100 records from a table.
    suppose i have a table xyz
    xyz:
    id name
    1 abc
    2 def
    i should get insert script for 100 rows like
    insert into xyz(id,name) values (1,'abc');
    insert into xyz(id,name) values (2,'def');
    i want 100 records data from all the tables from my database.
    thanks in advance to all.

    SQL> create table xyz (id number, name varchar2(10));
    Table created.
    SQL> insert into xyz values(1,'abc');
    1 row created.
    SQL> insert into xyz values(2,'def');
    1 row created.
    SQL> select 'insert into xyz values(id,name) values('||id||','''||name||''');' from xyz;
    'INSERTINTOXYZVALUES(ID,NAM
    insert into xyz values(id,name) values(1,'abc');
    insert into xyz values(id,name) values(2,'def');
    SQL>- - - - - - - - - - - - - - - - - - - - -
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com
    [Step by Step install Oracle on Linux and Automate the installation using Shell Script |http://kamranagayev.wordpress.com/2009/05/01/step-by-step-installing-oracle-database-10g-release-2-on-linux-centos-and-automate-the-installation-using-linux-shell-script/]

  • How should get last month value from report?

    Hi experts,
    How should last month value. For example
    jan    feb    march
    100   --       ---
    Here i want to get jan month value in march coloumn.

    Hi ,
    It is only show last month value. but my requirement is if last month is empty it should bring Before Last month.
    For Example
      Jan       Feb       Mar
    1000   
    i need if the Feb value is empty should come jan month value.

  • How to get last insert/update/delet row of a table?

    I hava a table A and table B which is a copy of A. I want to create a trigger to record the changes of A in B. So every time inserting/updating/deleting A I record the row inserted/updated/deleted in B, But I can't find a effiencial way to get the latest row changed.
    So is there any sys_var in oracle table like cur_rowid or something to record the latest inserted/updated/deleted in a table? I don't want to check a index or a table to get the max_seq_id again.

    user11228816 wrote:
    I hava a table A and table B which is a copy of A. I want to create a trigger to record the changes of A in B. So every time inserting/updating/deleting A I record the row inserted/updated/deleted in B, But I can't find a effiencial way to get the latest row changed.
    So is there any sys_var in oracle table like cur_rowid or something to record the latest inserted/updated/deleted in a table? I don't want to check a index or a table to get the max_seq_id again.Sounds like an ugly requirement, any reason you're not going for materialized views or advanced replication here?

  • How to get first 50 records from database using cmp beans 2.0?

    does any body know how i should write ejb-statment to do that?
    thanks
    winnicki

    if i run method for example findAll() and thereare
    500k recods my server will by out of memory ithink.
    Yes, you are right. I know some guys who wrote
    quite a large system in that style :-)
    Of course, the application didnt work in real life.
    Customer decided to throw the system away and later
    er some other guys rewrote it ....... in .NET
    What a pity! sigh

  • How to get the selection parameters from logical database into one of the t

    Hi Sap ABAP Champians,
    How to get the selection parameters from logical database into one of the tab in the tabstrip selection-screen.
    Please help me for this
    Thanks
    Basu

    Hi
    Thanks, that will work, but then I'll have to insert code into all my reports.
    I can see that "Application Server Control Console" is able to rerun a report.
    This must mean that the Report Server has access to the runtime parameters.
    But how?
    Cheers
    Nils Peter

  • How to get RMAN catalog information from Target database?

    Hi,
    How to get RMAN catalog information from Target database because i don't know about catalog database? is it possible?
    Thanks

    If you run RMAN backups of a target database using a Catalog schema in another database, the target is not aware of the catalog.
    The RMAN backup script would have the connection identifier for the Catalog.
    Hemant K Chitale

  • How to find last executed query on database and or schema.

    hi,
    how to find last executed query on database and or schema.
    yours sincerely

    Sessionwise if you wanna see means use v$session.. Because it will show execution time also so you can analyze it easily and get sql based on SID and serial number ..
    Try :
    select * from v$session;
    Regards..

  • How to get all the values from the dropdown menu

    How to get all the values from the dropdown menu
    I need to be able to extract all values from the dropdown menu; I know how to get all those values as a string, but I need to be able to access each item; (the value in a dropdown menu will change dynamically)
    How do I get number of item is selection dropdown?
    How do I extract a ?name? for each value, one by one?
    How do I change a selection by referring to particular index of the item in a dropdown menu?
    Here is the Path to dropdown menu that I'm trying to access (form contains number of similar dropdowns)
    RSWApp.om.GetElementByPath "window(index=0).form(id=""aspnetForm"" | action=""advancedsearch.aspx"" | index=0).formelement[SELECT](name=""ctl00$MainContent$hardwareBrand"" | id=""ctl00_MainContent_hardwareBrand"" | index=16)", element
    Message was edited by: testtest

    The findElement method allows various attributes to be used to search. Take the following two examples for the element below:
    <Select Name=ProdType ID=testProd>
    </Select>
    I can find the element based on its name or any other attribute, I just need to specify what I am looking for. To find it by name I would do the following:
    Set x = RSWApp.om.FindElement("ProdType","SELECT","Name")
    If I want to search by id I could do the following:
    Set x = RSWApp.om.FindElement("testProd","SELECT","ID")
    Usually you will use whatever is available. Since the select element has no name or ID on the Empirix home page, I used the onChange attribute. You can use any attribute as long as you specify which one you are using (last argument in these examples)
    You can use the FindElement to grab links, text boxes, etc.
    The next example grabs from a link on a page
    Home
    Set x = RSWApp.om.FindElement("Home","A","innerText")
    I hope this helps clear it up.

  • How to get last Build date of a dll in the real time target

    Info On My Project    
       I am working on LabWindows CVI 12.0 for development . This project is a real time application for hardware, which is having Phar Lap ETS as RTOS...  
    I am facing some problems while checking Build date of my Application file( .dll)
    I have tried to use GetFileDate API. But it is not supporting for realtime Target..
    So i have tried __DATE__ macro.. That also having some problems..
    How to get last Build date of a dll from the real time target  ??
    Please Help to solve this....
    Thanks
    Vaishakh A  K

    Please reply if any one have suggestion...

  • How to Get last page number in report 10g

    I want to get last page number in report but Current page number found from srw.get_page_num(n)
    but i want to get last page number for conditional formating like this
    srw.get_page_num(current_page)=last_page
    pls help me how can get last page number;
    pls help;
    thanks in advanced;

    Hi,
    you can use the Property Print Object On for this.
    Regards
    Rainer

  • How to get last date of the week

    hi,
    how to get last date of the week like FM WEEK_GET_FIRST_DAY gives the date of the first day of the week i need the date of the last day of the week..
    thnx

    data : p_week type KWEEK,
    p_Date type SYDATUM.
    p_week = <incoming value in week of year>
    CALL FUNCTION 'WEEK_GET_FIRST_DAY'
    EXPORTING
    week = p_week
    IMPORTING
    DATE = p_date
    EXCEPTIONS
    WEEK_INVALID = 1
    OTHERS = 2
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    To get the last day of the week.
    p_date = p_date + 6.
    You can find the available fm in the system from se37 transaction code.

Maybe you are looking for

  • Clean install - what's the 3rd install disk for?

    Hi all I did a clean install yesterday on my old G4 and so far so good. It's working much faster and the interet connection is alot stronger. But.... What is the 3rd Install Disk for? Have I missed something? Ta.

  • PowerPC Mac G4 (2.9) Expand Options

    Hi everyone, Just got a donation of PowerMac G4, so I get to work on it. Hopefully, there is no any firmware update needed on OS 9.1 before upgrading to OSX. I already did the upgrade. (I know this because I did an upgrade for PowerBook a while back

  • How import AVCHD video file ( Sony NEX 7) to FCPX ? Thank you !

    How import AVCHD video file ( Sony NEX 7) to FCPX ? Thank you !

  • EA1 - consumes a lot of CPU

    New 2.1.0.62 EA1 consumes a lot of CPU on my Macbook with MacOS 10.6.1. After I have opened two database connections (Oracle) everything seems to be fine (CPU usage 2% and below), but after I have executed some sql statements I will never get below 7

  • Jobs for oracle certified freshers

    hello, are there any jobs available for oracle SQL certified expert freshers