Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLITE INSERT with manual ID (primary Key)

Tags:

android

sqlite

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);
db.close();

Thanks,

like image 576
abdfahim Avatar asked Dec 08 '13 08:12

abdfahim


1 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

like image 139
laalto Avatar answered Sep 27 '22 22:09

laalto