Primary key from inserted row jdbc?

后端 未结 7 1227
野趣味
野趣味 2020-12-05 06:23

Is there a cross database platform way to get the primary key of the record you have just inserted?

I noted that this answer says that you can get it by Calling

相关标签:
7条回答
  • 2020-12-05 06:55

    extraneon's answer, although correct, doesn't work for Oracle.

    The way you do this for Oracle is:

    String key[] = {"ID"}; //put the name of the primary key column
    
    ps = con.prepareStatement(insertQuery, key);
    ps.executeUpdate();
    
    rs = ps.getGeneratedKeys();
    if (rs.next()) {
        generatedKey = rs.getLong(1);
    }
    
    0 讨论(0)
  • 2020-12-05 06:56

    for oracle, Hibernate uses NEXT_VALUE from a sequence if you have mapped a sequence for PKEY value generation.

    Not sure what it does for MySQL or MS SQL server

    0 讨论(0)
  • 2020-12-05 07:06

    For databases that conform to SQL-99, you can use identity columns: CREATE TABLE sometable (id INTEGER GENERATED ALWAYS AS IDENTITY(START WITH 101) PRIMARY KEY, ...

    Use getGeneratedKeys() to retrieve the key that was just inserted with executeUpdate(String sql, int autoGeneratedKeys). Use Statement.RETURN_GENERATED_KEYS for 2nd parameter to executeUpdate()

    0 讨论(0)
  • 2020-12-05 07:07

    Spring provides some useful support for this operation and the reference guide seems to answer your question:

    There is not a standard single way to create an appropriate PreparedStatement (which explains why the method signature is the way it is). An example that works on Oracle and may not work on other platforms is...

    I've tested this example on MySQL and it works there too, but I can't speak for other platforms.

    0 讨论(0)
  • 2020-12-05 07:12

    Have you tried the Statement.executeUpdate() and Statement.getGeneratedKeys() methods? There is a developerWorks article that mentions the approach.

    Also, in JDBC 4.0 Sun added the row_id feature that allows you to get a unique handle on a row. The feature is supported by Oracle and DB2. For sql server you will probably need a third party driver such as this one.

    Good luck!

    0 讨论(0)
  • 2020-12-05 07:12

    Just declare id column as id integer not NULL primary key auto_increment

    after this execute this code

    ResultSet ds=st.executeQuery("select * from user");
                    while(ds.next())
                    {
    
                     ds.last();
                    System.out.println("please note down your registration id  which is "+ds.getInt("id"));
                    }
                    ds.close();
    

    the above code will show you the current row's id

    if you remove ds.last() than it will show all values of id column

    0 讨论(0)
提交回复
热议问题