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

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

}

最佳答案

通过运行类似于下面的选择查询来检查 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);
}

关于Android sqlite 如果行存在则更新否则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34156954/

相关文章:

mysql - 在子查询mysql中使用父查询的id列

Python 和 SQLite : Not all arguments converted during string formatting error

Android 数据库助手单例和同步

ios - FMDB 多条记录更新查询

java - 仅使用一种颜色生成渐变

java - 为什么 super() 构造函数不采用与父构造函数相同的参数?

android - 使用 Push Sharp 的谷歌云消息传递

java - 在不连接的情况下获取 WiFi 的 SSID?

php - 将标签插入表格的最有效方法是什么

mysql - 如何将 ng-value 发布到 mysql 数据库