Android sqlite如果rowid exsist更新其他插入

时间:2015-12-08 13:18:31

标签: android mysql sqlite insert-update

我必须通过我的android应用程序给Android应用程序的用户评级,一旦我给出评级它将存储在sqlite数据库中,再次我给同一应用程序的评级它将再次存储在数据库中,我想如果应用程序的行ID已经存在它将更新表,否则将值插入表中,我知道它非常简单,但它给我带来麻烦,谢谢你的帮助......    我的代码:     评级栏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();
    }

}

2 个答案:

答案 0 :(得分:1)

通过运行类似下面的选择查询来检查rowid是否存在:

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);
}

答案 1 :(得分:0)

尝试更新行。如果找不到,请插入:

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();
    }
}