H2数据库中的自动增量ID

eri*_*riq 49 database h2 auto-increment

是否有一个表的auto_incrementing BIGINT ID.它可以这样定义

id bigint auto_increment
Run Code Online (Sandbox Code Playgroud)

但这没有效果(它不会自动增加).我想插入所有字段,但ID字段 - ID字段应由DBMS提供.或者我需要调用一些东西来增加ID计数器吗?

Tho*_*ler 125

这个对我有用.JDBC URL:jdbc:h2:~/temp/test2

drop table test;
create table test(id bigint auto_increment, name varchar(255));
insert into test(name) values('hello');
insert into test(name) values('world');
select * from test; 
Run Code Online (Sandbox Code Playgroud)

结果:

ID  NAME  
1   hello
2   world
Run Code Online (Sandbox Code Playgroud)

  • 另一种使用`default`的语法存在:`insert into test values(默认为'hello');`对于包含大量字段的表有用. (9认同)
  • 如果你能给我的答案+1,我会很高兴:-) (3认同)
  • 谢谢!你不需要把它提高,那没关系.我只是不明白为什么有人会投票给-1以获得正确答案......可能是某些人不理解这个问题. (3认同)

Bas*_*que 18

IDENTITY

现代方法使用该IDENTITY类型,以自动生成一个递增的64位长整数。

H2中使用的这种单字语法是SQL:2003标准中GENERATED … AS IDENTITY定义的缩写形式。参见PDF文档SQL:2003已发布中的摘要。其他数据库正在实现这一点,例如Postgres

CREATE TABLE event_ ( 
    pkey_ IDENTITY NOT NULL PRIMARY KEY ,  -- ? `identity` = auto-incrementing long integer.
    name_ VARCHAR NOT NULL ,
    start_ TIMESTAMP NOT NULL , 
    stop_ TIMESTAMP NOT NULL 
) ;
Run Code Online (Sandbox Code Playgroud)


bel*_*kiy 6

很简单的:

id int auto_increment primary key
Run Code Online (Sandbox Code Playgroud)

H2将自动创建Sequence对象


eri*_*icj 5

您还可以使用default

create table if not exists my(id int auto_increment primary key,s text);
insert into my values(default,'foo');
Run Code Online (Sandbox Code Playgroud)