How to update KEY_ROWID after deleting a row in SQLite database

前端 未结 2 1955
离开以前
离开以前 2021-01-21 14:19

How can I update the KEY_ROWID number in SQLite database after deleting a row from the database? CASE 1: For example, if I have five rows in the database, maximum KEY_ROWID is

相关标签:
2条回答
  • 2021-01-21 15:07

    You can reset the sequences if you're deleting all data;

    DELETE FROM test;
    DELETE FROM sqlite_sequence WHERE name='test';
    

    As for renumbering primary keys when there is still data in the table, I'd sincerely advise against it, since any foreign keys that reference your table will be broken.

    0 讨论(0)
  • 2021-01-21 15:09

    The solution is that rewriting the table with a new array or list ;

    reWriteTable is will allow automatic sorting of rows.

    private void reWriteTable(){
        if(db.listOfDate().size()!=0){
            String[] name =new String[db.listOfDate().size()] ;
            String[] note=new String[db.listOfDate().size()] ;
            String[] date =new String[db.listOfDate().size()];
            String[] time =new String[db.listOfDate().size()];
            String[] total =new String[db.listOfDate().size()];
    
            for(int i=0;i<db.listOfDate().size();i++) {
                String currentString =db.listOfDate().get(i) ; // 0,1,2,3
                separated = currentString.split("-");  //Take words between "-" from Database 
                name[i]=separated[1];
                note[i]=separated[2];
                date[i]=separated[3];
                time[i]=separated[4];
                total[i]=separated[1]+"-"+separated[2]+"-"+separated[3]+"-"+separated[4];
            }
            db.deleteTable();
            //db=new Database(MainActivity.this);
            for(int i=0;i<total.length;i++) {
                Log.d("TAG",String.valueOf(total.length)+"  "+total[i]);
                String currentString =total[i] ; // 0,1,2,3
                separated = currentString.split("-");  //Take words between "-" from Database 
                name[i]=separated[0];
                note[i]=separated[1];
                date[i]=separated[2];
                time[i]=separated[3];
                // total[i]=separated[1]+"-"+separated[2]+"-"+separated[3]+"-"+separated[4];
                db.addData(name[i],note[i],date[i],time[i]);
            }
        }
    
    }
    

    Define deleting table in Database.java ;

     protected void deleteTable(){
            SQLiteDatabase db=this.getWritableDatabase();
            db.execSQL(" drop table if exists " + TABLO_UYGULAMALAR + ";");
            onCreate(db);
    
        }
    
    0 讨论(0)
提交回复
热议问题