简体   繁体   中英

Increment value of a table ID for each INSERT

I'm using PostgreSQL with all my tables setup. I currently have a table called comments with a primary key called comment_id which is a VARCHAR of length 4.

I have a form setup to insert a new comment into the database but I'm confused as to how I will get my Java servlet to ++ the comment_id from it's previous value. Eg 0001 to 0002.

You don't want to use a VARCHAR for your id column. In postgres you can create a sequence and then get the next value of that sequence for each insert.

here are the docs

Basically, you do something like

CREATE SEQUENCE mysequence START 101

Then, when you insert you do something like

INSERT INTO my_comment values (nextval('mysequence'), 'this is my comment');

Use the serial pseudo data type to begin with. It creates and attaches the sequence object automatically and sets the DEFAULT to nextval() from the sequence. It does all you need. Effective type for the column is integer . There is also bigserial . Just follow the link to the manual.

CREATE TABLE comments (
    comment_id serial PRIMARY KEY
   ,comment text NOT NULL
   );

You can ignore the column for INSERT commands:

INSERT INTO my_comment (comment)
VALUES ('My comment here');

comment_id is filled in automatically.
But you should always provide a column list for INSERT . If you later change table layout, your code may break in hurtful ways. It may be ok to skip the column list for ad-hoc commands or when the table structure is guaranteed (like when you created the table in the same transaction). Other than that, provide a column list!

If you want the resulting comment_id back, without another round trip to the server:

INSERT INTO my_comment (comment)
VALUES ('My comment here');
 comment_id;

Details in the excellent manual here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM