Java Postgresql 如何自动生成主键

huangapple go评论78阅读模式
英文:

Java Postgresql How to generate primary key automatically

问题

我想在使用INSERT INTO时自动生成一个新的ID(主键):

    String id = "1";
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TABLE (id) VALUES(?)");
    prep.setString(1, id); // 生成新的ID
    prep.executeUpdate();

实际上,我将1设置为我的id,但是如果我想要生成更多的INSERT INTO,如何使用新的ID插入新的值?

英文:

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 ?

答案1

得分: 2

使用身份列:

创建表 foo 
(
  id integer 主键 生成总是作为身份列, 
  some_column 文本, 
  ... 
)

然后使用 PreparedStatement.getGeneratedKeys()

int id = -1;
PreparedStatement prep = conn.prepareStatement("INSERT INTO 表名 (some_column) VALUES(?)", Statement.RETURN_GENERATED_KEYS);
prep.setString(1, "某个值");
prep.executeUpdate();
ResultSet rs = prep.getGeneratedKeys();
if (rs.next()) {
  id = rs.getInt(1);
}
英文:

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);
}

huangapple
  • 本文由 发表于 2020年10月9日 01:46:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64268012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定