当想要更新取决于当前值时如何通过 ContentValues 使用 sqlite 更新以及如何检索结果?
How can use sqlite update via ContentValues when want to update depend on current value and how can retrieve the Result?
我在 sqlite 中有一个情况可以作为一个例子:我的 table 有两个字段,"_id" 和 "_score" 。我有一条 _id=1,_score=10 的记录。我想将此行更新为比当前值 (10) 多 5 个数字。在 SQL 我可以像这样简单地做:
Update my_table set _score = _score + 5 where _id = 1
但在 sqlite 中我有这些我不知道如何将其修复为我想要的东西:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(MY_TABLE,values,"_id = ?",new String[]{String.valueOf(my_id)});
另一个问题是返回值。我想在上面的例子中我给出
id = 1
1 行受到影响。但我想知道:有没有办法检索更新列的值(在我的示例中我想给出“15”)。我们从
获取的 SQL 服务器中的一些东西
"@@ROWCOUNT" or "@@fetch_status"
希望描述的好。谢谢。
对于更新分值的第一个问题,请尝试以下操作:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(my_table, values, _id + " = ?",
new String[] { String.valueOf(my_id) });
}
Android的update()
函数只能设置固定值。
要执行您的 SQL 语句,您必须使用 execSQL()
:
db.execSQL("Update my_table set _score = _score + 5 where _id = 1");
在SQLite中,UPDATE语句不return任何数据(受影响的行数除外)。要获取旧数据或新数据,您必须分别执行SELECT。
我在 sqlite 中有一个情况可以作为一个例子:我的 table 有两个字段,"_id" 和 "_score" 。我有一条 _id=1,_score=10 的记录。我想将此行更新为比当前值 (10) 多 5 个数字。在 SQL 我可以像这样简单地做:
Update my_table set _score = _score + 5 where _id = 1
但在 sqlite 中我有这些我不知道如何将其修复为我想要的东西:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(MY_TABLE,values,"_id = ?",new String[]{String.valueOf(my_id)});
另一个问题是返回值。我想在上面的例子中我给出
id = 1
1 行受到影响。但我想知道:有没有办法检索更新列的值(在我的示例中我想给出“15”)。我们从
获取的 SQL 服务器中的一些东西"@@ROWCOUNT" or "@@fetch_status"
希望描述的好。谢谢。
对于更新分值的第一个问题,请尝试以下操作:
ContentValues values = new ContentValues();
values.put("_score", my_value);
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
int id = db.update(my_table, values, _id + " = ?",
new String[] { String.valueOf(my_id) });
}
Android的update()
函数只能设置固定值。
要执行您的 SQL 语句,您必须使用 execSQL()
:
db.execSQL("Update my_table set _score = _score + 5 where _id = 1");
在SQLite中,UPDATE语句不return任何数据(受影响的行数除外)。要获取旧数据或新数据,您必须分别执行SELECT。