如何将数据插入 id = ... 的现有列?
How to insert data to existing column where id = ...?
我在我的数据库中创建了 table 分数(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 参数的行。我该怎么做?
您想要的是更新列 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()
return 影响的行数,所以你的方法 updateScore()
将 return true
如果指定的行 id
已更新。
我在我的数据库中创建了 table 分数(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 参数的行。我该怎么做?
您想要的是更新列 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()
return 影响的行数,所以你的方法 updateScore()
将 return true
如果指定的行 id
已更新。