简体   繁体   中英

how to delete a row from table in derby where ID column increment by 1?

i have problem with my table and exactly in ID column, when i insert record>>the ID will increment by 1 automatically, but the problem that when i delete old record and insert new record the increment continue counting and the ID of new record didn't take the ID of old record by sequence ;

my delete statment : String Q="DELETE FROM EMPLOYEE ( ID , NAME) WHERE NAME='"+lst1.getSelectedValue()+"'"; stmt.execute(Q); String Q="DELETE FROM EMPLOYEE ( ID , NAME) WHERE NAME='"+lst1.getSelectedValue()+"'"; stmt.execute(Q);

create statment: stmt.execute("CREATE TABLE EMPLOYEE(ID INTEGER NOT NULL PRIMARY KEY" + " GENERATED ALWAYS AS IDENTITY(START WITH 1, INCREMENT BY 1)" + ",NAME varchar(50),BIRTHDAY varchar(50),BIRTHMONTH varchar(50)" + ",BIRTHYEAR varchar(50),SEX varchar(50),DEPARTMENT varchar(50))");}

insert statment: String Query="INSERT INTO EMPLOYEE(NAME , BIRTHDAY , BIRTHMONTH , " + "BIRTHYEAR , SEX , DEPARTMENT) VALUES('"+txname.getText()+"','" + ""+compd.getSelectedItem()+"','"+compm.getSelectedItem()+"','" + ""+compy.getSelectedItem()+"','"+composx.getSelectedItem()+"','" + ""+txdep.getText()+"')"; stmt.execute(Query); String Query="INSERT INTO EMPLOYEE(NAME , BIRTHDAY , BIRTHMONTH , " + "BIRTHYEAR , SEX , DEPARTMENT) VALUES('"+txname.getText()+"','" + ""+compd.getSelectedItem()+"','"+compm.getSelectedItem()+"','" + ""+compy.getSelectedItem()+"','"+composx.getSelectedItem()+"','" + ""+txdep.getText()+"')"; stmt.execute(Query); thanks very good firstly for answer and try help

You can solve that on the application side adopting the strategy of not really deleting the row, but adding a boolean field 'deleted', 0 if not deleted or 1 if deleted.

This in the case you want to avoid holes in the ID sequence.

Otherwise you live with the fact that there will be holes in the ID sequence. What is the problem with that?

By the way, what is the DB you are working with?

I read you comment. The point is that all the DBs append new records at the end of the table. So if you want to reuse IDs you have these possibilities:

  1. make a piece of code to check if there is a free ID in the sequence and use it in INSERT
  2. make a piece of code to save free IDs somewhere and reuse them when you insert.

In other terms: you have to manage IDs directly. The way the DB manages them is:

  1. Deleting a record produces a hole that will not be filled automatically
  2. Adding a new record increment the last id

Regards

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