Home » Android » android – SQLITE INSERT with manual ID (primary Key)

android – SQLITE INSERT with manual ID (primary Key)

Posted by: admin June 15, 2020 Leave a comment


Can I insert into a SQLITE database using db.insert method with manual ID [PRIMARY KEY AUTO INCREMENT] value? Or I have to do it with rawQuery method with SQL command?

mylibman ... // Is a custom class containing all values
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
//values.put(KEY_ID, mylibman.getBookid()); //If I put this line, ID always becomes zero 
values.put(KEY_NAME, mylibman.getBookname());
values.put(KEY_PRINT_NAME, mylibman.getPrintname());
long numrow = db.insert(TABLE_NAME, null, values);


How to&Answers:

Yes, you can explicitly define the value for an INTEGER PRIMARY KEY AUTOINCREMENT column.
If you try to re-insert an existing key, you’ll get “PRIMARY KEY must be unique” error.

The automatic rowid generation only only takes place if the column value is not given, or is given as NULL.

Reference: http://www.sqlite.org/autoinc.html