Auto Increment after delete in MySQL

后端 未结 17 1808
醉酒成梦
醉酒成梦 2020-11-22 09:50

I have a MySQL table with a primary key field that has AUTO_INCREMENT on. After reading other posts on here I\'ve noticed people with the same problem and with varied answer

17条回答
  •  逝去的感伤
    2020-11-22 10:25

    here is a function that fix your problem

        public static void fixID(Connection conn, String table) {
    
        try {
            Statement myStmt = conn.createStatement();
            ResultSet myRs;
            int i = 1, id = 1, n = 0;
            boolean b;
            String sql;
    
            myRs = myStmt.executeQuery("select max(id) from " + table);
            if (myRs.next()) {
                n = myRs.getInt(1);
            }
            while (i <= n) {
                b = false;
                myRs = null;
                while (!b) {
                    myRs = myStmt.executeQuery("select id from " + table + " where id=" + id);
                    if (!myRs.next()) {
                        id++;
                    } else {
                        b = true;
                    }
                }
    
                sql = "UPDATE " + table + " set id =" + i + " WHERE id=" + id;
                myStmt.execute(sql);
                i++;
                id++;
            }
    
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题