简体   繁体   中英

Java Postgresql How to generate primary key automatically

I woudlike to generate automatically a new id (primary key) when I use INSERT INTO :

    String id = "1";
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TABLE (id) VALUES(?)");
    prep.setString(1, id); // generate new id 
    prep.executeUpdate();

Actually I set 1 to my id but if I want to generate more INSERT INTO How can I INSERT INTO new value with new id?

Use an identity column:

create table foo 
(
  id integer primary key generated always as identity, 
  some_column text, 
  ... 
)

Then use PreparedStatement.getGeneratedKeys()

int id = -1;
PreparedStatement prep = conn.prepareStatement("INSERT INTO TABLE (some_column) VALUES(?)", Statement.RETURN_GENERATED_KEYS);
prep.setString(1, "some value");
prep.executeUpdate();
ResultSet rs = prep.getGeneratedKeys();
if (rs.next()) {
  id = rs.getInt(1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM