java - 基于另一列数据的Android Java SQLite rowid
问题描述
解决方案已被选中,但还有另一个有效。我会在下面添加
我整天都在这。在问题的另一个方面有帮助,但我又被难住了。如何获取列中包含某些数据的行的rowid?我需要以 int 或字符串形式返回的 rowid。示例数据:
_id|firstname|lastname
1 |Bob |Dole
2 |Richard |Simmons
3 |Steven |King
那么,如果我想在 lastname = "Simmons" 的情况下获取 rowid,我应该使用什么代码?运行 select 语句后,我认为 c.getPosition() 会这样做,但它返回 -1。这是我到目前为止所得到的:
String where = "SELECT rowid, * FROM masterRecord WHERE masNameCol='" + name + "'"; //name is a variable passed from another activity
Cursor c = db.rawQuery(where, null);
String rowid = "_id = " + c.getPosition(); //This always returns -1. In this example, I need it to be 2
ContentValues newValues = new ContentValues();
newValues.put(KEY_MASNAMECOL, rowid);
newValues.put(KEY_MASTIMECOL, newTime);
c.close();
return db.update(masterRecord, newValues, rowid, null) != 0;
请注意,如果我将 return 语句中的 rowid 替换为“_id=2”,它将按预期工作。所以我把它缩小到只需要以某种方式获得这个数字。
其他解决方案
String where = "SELECT rowid, * FROM " + masterName + " WHERE masNameCol='" + name + "'";
int rowid = 0;
Cursor c = db.rawQuery(where, null);
c.moveToFirst(); //Needed this line
if (c.getCount() > 0) { //And this if statement
rowid = c.getInt(c.getColumnIndex("_id"));
}
ContentValues newValues = new ContentValues();
newValues.put(KEY_MASNAMECOL, rowid);
newValues.put(KEY_MASTIMECOL, newTime);
c.close();
return db.update(masterName, newValues, "_id =" + rowid, null) != 0;
解决方案
您可以在不先获取其 rowid 的情况下更新表:
String where = "masNameCol = ?";
ContentValues newValues = new ContentValues();
newValues.put(KEY_MASNAMECOL, "somevaluehere"); // what value do you want this column to be updated?
newValues.put(KEY_MASTIMECOL, newTime);
return db.update(masterRecord, newValues, where, new String[] {name}) != 0;
请注意,如果列masNameCol
不是唯一的,这将使用变量的值更新所有行name
。
推荐阅读
- javascript - TinyMCE 5:禁用编辑器但允许复制文本
- intellij-idea - 使用 defresource 时无法解析 Arg
- c# - C# - InitializeComponent 的问题
- node.js - 我有 2 个相同的 ID,但是当我尝试查找它们是否相等时,它们不相等
- c# - 跨多个服务和 .net 版本重用类型
- macos - 如何启动设置了环境变量的 mac (osx/macos) 应用程序?
- r - 在 ggplot 的图形中添加自定义线
- javascript - 如何设置 css 和 javascript 来解决带有粘性标题的搜索结果跳转?
- android - 如何将图像文件存储到 FirebaseStorage
- javascript - 使除下拉列表之外的整个 DIV 可点击