This may be duplicate question but am confused as am new for sql and android am getting response from server need to save it in sqlite db if values in the table already exis
you must check if it is exist. Do it like this code:
private Cursor selectOneItem(int id) {
String strQuery = String.format(
"SELECT * FROM %s WHERE %s = %s", Model_Task_List.KEY_table,
Model_Task_List.KEY_id, id);
Cursor cur = db.rawQuery(strQuery , null);
return cur;
}
use above code to your insert function like below:
public void insert(Model_Task_List modelobj) {
Cursor cur = selectOneNews(modelobj.getTaskID());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Model_Task_List.KEY_username, modelobj.getUserName());
values.put(Model_Task_List.KEY_subject,modelobj.getSubject());
values.put(Model_Task_List.KEY_task, modelobj.getTaskStatus());
values.put(Model_Task_List.KEY_taskid,modelobj.getTaskID());
values.put(Model_Task_List.KEY_owner,modelobj.getUserid());
if (cur == null || cur.getCount() == 0) {
db.insert(Model_Task_List.KEY_table, null, values);
} else {
String[] args = {modelobj.getTaskID() + ""};
db.update(Model_Task_List.KEY_table, values,
Model_Task_List.KEY_id + "=?", args);
}
db.close();
}
replace is just like insert, it just checks if there is duplicate key and if it is it deletes the row, and inserts the new one, otherwise it just inserts
you can do this if there is for example unique index of (Model_Task_List.KEY_taskid) and if you type the following command
REPLACE INTO Model_Task_List.KEY_table(Model_Task_List.KEY_taskid,Model_Task_List.KEY_task,Model_Task_List.KEY_username,Model_Task_List.KEY_subject) VALUES ('111',3,50,90 )
and there already exists a row with Model_Task_List.KEY_taskid= '111' it will be replaced
CREATE UNIQUE INDEX idx_name_type ON Model_Task_List.KEY_table(Model_Task_List.KEY_taskid)
EDIT: a quick note - REPLACE always DELETES and then INSERTs, so it is never a very good idea to use it in heavy load because it needs exclusive lock when it deletes, and then when it inserts
some of the database engines have
INSERT ... ON DUPLICATE KEY UPDATE ...
Link
The update()
function returns how many rows were affected.
So if there were none, you know that you must insert instead:
void updateIfExistsElseInsert(...) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = ...;
values.put( /* all except the ID */ );
int rows = db.update(KEY_TABLE, values, KEY_ID + " = " + id, null);
if (rows == 0) {
values.put(KEY_ID, id);
db.insert(KEY_TABLE, null, values);
}
}