为提高效率,提问时请提供以下信息,问题描述清晰可优先响应。
【DM版本】:DM8(1-2-174-2022.11.21-175072-20024-ENT)
【操作系统】: windows
【CPU】: x86
【驱动版本】: dm安装包自带的8.1.2.174
【问题描述】*:使用序列和触发器为表自动生成id,但是在jdbc中返回的id值与实际的id值不一致。
表:
create table test(
id int primary key,
name varchar(32)
);
序列与触发器,序列设置的起始值为1000
CREATE SEQUENCE "TEST_SEQ" MINVALUE 1 NOMAXVALUE INCREMENT BY 1 START WITH 1000 NOCACHE;
CREATE OR REPLACE TRIGGER "TRIGGER_TEST_AUTO_ID"
before insert on test for each row WHEN (new.id is null) begin
select TEST_SEQ.nextval into:new.id from dual;
end;
/
ALTER TRIGGER "TRIGGER_TEST_AUTO_ID" ENABLE;
代码
public static void statement() throws SQLException {
DmdbConnectionPoolDataSource dataSource = new DmdbConnectionPoolDataSource();
dataSource.setURL("jdbc:dm://127.0.0.1:5236");
dataSource.setUser("test");
dataSource.setPassword("123456789");
Connection connection = dataSource.getConnection();
String sql = "insert into test(name) values (?) ";
PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1,"test");
preparedStatement.executeUpdate();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
while (generatedKeys.next()){
System.out.println(generatedKeys.getLong(1));
}
}
结果代码返回的值是:0,实际插入数据的id是1018。
建表时使用自增列
create table test(
id int primary key IDENTITY(1000,1),
name varchar(32)
);