【问题标题】:How to insert data to existing column where id = ...?如何将数据插入到 id = ...的现有列?
【发布时间】:2021-02-06 13:29:26
【问题描述】:

我在我的数据库中创建了带有分数的表(10 条记录)。它们现在是空的,但我希望在用户进行一些测验后更新它们。

现在我的函数看起来像这样:

public boolean insertScore(float score, int id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("Score", score);
        long result = db.insert("Scores" , null, contentValues);
        if (result == -1){
            return false;
        }
        else{
            return true;
        }
    }

但我想将数据放到 id 等于 id 参数的行中。我该怎么做?

【问题讨论】:

    标签: java android sqlite android-sqlite


    【解决方案1】:

    您想要的是更新列score 的现有值而不是插入新行:

    public boolean updateScore(float score, int id){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("Score", score);
        long result = db.update("Scores", contentValues, "id = ?", new String[] {String.valueOf(id)});
        db.close();
        return result > 0;
    }
    

    update() 方法返回受影响的行数,因此如果指定id 的行已更新,您的方法updateScore() 将返回true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2010-09-25
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      相关资源
      最近更新 更多