Reputation:
I wanted to update my existing table with new values but some of them are fresh. I have written code for updating the table, but how can I do both operations(update & insert) simultaneously.
Upvotes: 1
Views: 944
Reputation: 1780
Just use replace() method in SQLiteDatabase. Its simply insert a new row if no row with same key is not exists in database. Otherwise it replaces the existing row.. Its simple than other ways.. For more info refer the documentation..
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Upvotes: 1
Reputation: 28823
Try something like this:
String username="xyzName";
Cursor cur_user = my_db.rawQuery("SELECT _id from user_info where user_name ='"
+ username + "'", null);
if (cur_user.getCount() > 0) {
// User exists. Update information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
String whereClause = "user_name = '" + username + "'";
try {
my_db.update("user_info", cvUserInfo, whereClause, null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Insert the information in database.
ContentValues cvUserInfo = new ContentValues();
cvUserInfo.put("status", status_id);
cvUserInfo.put("user_name", username);
my_db.insert("user_info", null, cvUserInfo);
}
You will need to have one column except id, on which you can check. I had user name as a unique column to check for existing record.
Hope this helps.
Upvotes: 0