首页 > 解决方案 > 基于另一列数据的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;

标签: javaandroidsqlitesql-updateandroid-sqlite

解决方案


您可以在不先获取其 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


推荐阅读