Access to auto increment identity field after SQL insert in Java

前端 未结 5 593
栀梦
栀梦 2020-12-28 18:00

Any advice on how to read auto-incrementing identity field assigned to newly created record from call through java.sql.Statement.executeUpdate?

I know h

5条回答
  •  误落风尘
    2020-12-28 18:11

    The following snibblet of code should do ya':

    PreparedStatement stmt = conn.prepareStatement(sql, 
                                     Statement.RETURN_GENERATED_KEYS);
    // ...
    
    ResultSet res = stmt.getGeneratedKeys();
    while (res.next())
        System.out.println("Generated key: " + res.getInt(1));
    

    This is known to work on the following databases

    • Derby
    • MySQL
    • SQL Server

    For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to SELECT NEXTVAL(...) for the sequence in question.

    Note that the parameters for executeUpdate(...) are analogous.

提交回复
热议问题