Android sqlite 如果行存在则更新否则插入

Android sqlite if rowid exsist update else insert

我必须通过我的 android 应用程序给 android 应用程序一个用户评级,一旦我给出评级,它将存储在 sqlite 数据库中,我再次给同一个应用程序评级将再次存储在数据库中,我想如果应用程序的行 ID 已经存在,它将更新 table,否则将值插入 table,我知道这很简单,但对我来说很麻烦,谢谢您的帮助... 我的代码: 评分栏 setOnRatingBarChangeListener:

   ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        public void onRatingChanged(RatingBar ratingBar, float rating,
                                    boolean fromUser) {
            txtRatingValue.setText(String.valueOf(rating * 20) + "Rating");
            Log.d("Raating ", String.valueOf(rating));
            strA[21] = String.valueOf(rating);
            String userRating=String.valueOf(rating);
            curRate=Float.parseFloat(userRating);
           DataBaseHelper db = new DataBaseHelper(Activity1.this);
            db.insertuserrate(strA, cxt);

        }
    });
   public  void insertuserrate(String Str[],Context cxt) {

    // TODO Auto-generated method stub
    Cursor c = null;
    String strId="";
    ArrayList<String> userRatepoit= new ArrayList<String>();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
     {
            values.put(KEY_RID, Str[0]);
            values.put(ALL_name, Str[1]);
            values.put(ALL_isbn, Str[2]);
            etc...
            values.put(ALL_book_rating, Str[20]);
            values.put(ALL_book_userrating, Str[21]);
         db.insert(TABLE_USERRATE, null, values);
         Log.d("inserted success", TABLE_USERRATE);
            // Closing database connection
        }
try {

db.close();
}catch(Exception e)
{
e.printStackTrace();
}
    }

    catch(Exception e)
    {
        e.printStackTrace();
    }

}

检查 rowid 是否存在 运行 select 类似于下面的查询:

public boolean rowIdExists(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("select 1 from " + TABLE_USERRATE
            + " where row_id=?", new String[] { "" + id });
    boolean exists = (cursor.getCount() > 0);
    cursor.close();
    db.close();
    return exists;
}

然后在您当前的实现中使用它来确定是插入还是更新:

if (rowIdExists(someID)) {
    db.updateuserrate(strA, cxt);
} else {
    db.insertuserrate(strA, cxt);
}

只需尝试更新该行。如果未找到,请插入:

void updateOrInsert(...) {
    SQLiteDatabase db = getWritableDatabase();
    try {
        ContentValues cv = new ContentValues();
        cb.put(...); // all except the ID
        if (db.update(TABLE_USERRATE, cv,
                      KEY_RID + " = " + Str[0], null) == 0) {
            cv.put(KEY_RID, Str[0]);
            db.insert(TABLE_USERRATE, null, cv);
        }
    } finally {
        db.close();
    }
}