简体   繁体   English

自动递增ID中断序列

[英]Auto Increment ID break the Sequence

My program has an auto incremented ID with the format of ITM001, ITM002... . 我的程序有一个ITM001, ITM002...格式的自动递增ID。 But after ITM009, ITM0010 the sequence is broken and goes back to ITM001 . 但是在ITM009, ITM0010之后ITM009, ITM0010序列中断,并返回到ITM001 Because of that I'm getting ITM0010 as next item ID instead of ITM0011 . 因此,我将ITM0010作为下一个项目ID而不是ITM0011 Please help me to understand how should I write the query to continue the sequence. 请帮助我了解如何编写查询以继续执行序列。

ITM001
**ITM0010**
ITM002
ITM003
ITM004
ITM005
ITM006
ITM007
ITM008
ITM009
   Connection conn = DBConnection.conn();
      String sql = "select itemId from ItemMain";
       ResultSet res = DBHandller.getData(sql, conn);
        if (res.last()) {
              String lastid = res.getString("itemId");
               return lastid;
        }
        return null;   
/////////////////////////////////////////////////////////////////////////////


              String itemID = ItemController.getItemID();

              String[] split = itemID.split("ITM",0);
              int num = Integer.parseInt(split[1]);
              itemID = "ITM00"+ (num+1);
              txtitemID.setText(itemID);

The problem is that you're using split on 0, and there are several 0's in your String after you increment, for instance: 问题是您正在使用split on 0,并且在递增后String中有多个0,例如:

    String[] split = itemID.split("ITM",0);
    int num = Integer.parseInt(split[1]);
    String second = "ITM00" + (num + 1);
    System.out.println(second);
    System.out.println(Arrays.toString(second.split("0")));

This will output: 这将输出:

[ITM, , 1]

Since the last 0 will also be split. 由于最后0也将被拆分。

Something like: 就像是:

String itemID = "ITM009";
int num = Integer.parseInt(itemID.substring(itemID.indexOf("0")));
String second = "ITM0" + String.format("%02d", num + 1);
System.out.println(second);

Will give you what you want probably, but you need to figure out how many digits you want your key to have and adapt accordingly. 可能会给您您想要的东西,但是您需要弄清楚您的钥匙要拥有多少位数并进行相应的调整。

You are implicitly sorting on a VARCHAR field. 您正在对VARCHAR字段进行隐式排序。

SELECT a.a FROM (
    SELECT 'a001' [a]
    UNION ALL
    SELECT 'a009' [a]
    UNION ALL
    SELECT 'a0010' [a]
) a ORDER BY a

a001
a0010
a009

The last id you pick up will always be 009 so the next one you create will always be 0010. 您选择的最后一个ID始终为009,因此您创建的下一个ID始终为0010。

If you front padded the "10" with 1 "0" instead of two the implicit ascending sorting would be correct. 如果用1“ 0”而不是2填充“ 10”,则隐式的升序排序是正确的。 "001 ... 009, 010" “ 001 ... 009,010”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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