英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论