[英]How to get sequence.nextval from SQL in JDBC?
I have 5 tables where I use the same sequence's next value.我有 5 个表,我在其中使用相同序列的下一个值。 The problem is, the subsequent tables gets a bigger value than the previous ones.问题是,后续表获得的值比以前的表大。
My code is like this:我的代码是这样的:
String sql = "INSERT INTO table1(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "bar");
ps.executeUpdate();
sql = "INSERT INTO table2(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "tar");
ps.executeUpdate();
sql = "INSERT INTO table3(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "par");
ps.executeUpdate();
sql = "INSERT INTO table4(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "car");
ps.executeUpdate();
sql = "INSERT INTO table5(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "rar");
ps.executeUpdate();
My sequence is like this:我的顺序是这样的:
CREATE SEQUENCE "ID_SEQ" MINVALUE 1 MAXVALUE 9999999999 INCREMENT BY 1 START WITH 10 CACHE 20 NOORDER NOCYCLE ;
Now when I look at my tables, table1's ID is 10, but table2's ID is 11 and table3's ID is 12..... I want all the tables' IDs to be same.现在,当我查看我的表时,table1 的 ID 为 10,但 table2 的 ID 为 11,table3 的 ID 为 12..... 我希望所有表的 ID 都相同。 What should I do?我该怎么办? Thank you in advance.先感谢您。
edit: Had to include more tables than 2 to have more general question编辑:必须包含多于 2 个表才能有更一般的问题
Actually I found the answer online.其实我在网上找到了答案。 I need to do this:我需要这样做:
String sql = "select ID_SEQ.nextval from DUAL";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next())
int nextID_from_seq = rs.getInt(1);
And when I insert this value to database, I type this:当我将此值插入数据库时,我输入:
String sql2 = "INSERT INTO table1(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "tar");
ps.executeUpdate();
sql2 = "INSERT INTO table2(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "par");
ps.executeUpdate();
...
...
The first string sql is "select ID_SEQ.nextval from DUAL."第一个字符串 sql 是“select ID_SEQ.nextval from DUAL”。 That "DUAL" in the end is not table name or anything.最后那个“DUAL”不是表名或任何东西。 It's just one of the given or provided functionality by oracle.它只是 oracle 给定或提供的功能之一。 I can get any sequence's nextval by using it.我可以通过使用它来获得任何序列的 nextval。
You can use id_seq.currval
for the second table.您可以将id_seq.currval
用于第二个表。 It will reuse the same id.它将重用相同的 id。
sql = "INSERT INTO table2(id, name) VALUES (id_seq.currval, ?)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.