最近添加到数据库的记录

时间:2022-09-01 21:02:13

How should i get most recent added record from database, where COL_2 should == param that I pass into it. I can get all records where COL_2 is equal to param with this code, but I need only recent one

如何从数据库中获取最近添加的记录,其中COL_2应该= param,并将其传递给它。我可以获得COL_2与此代码的参数相等的所有记录,但我只需要最近的记录

    public Cursor getRowsLast(String param) {
    SQLiteDatabase db = helper.getWritableDatabase();
    String[] COLS = new String[]{DatabaseHelper.COL_1,DatabaseHelper.COL_2, DatabaseHelper.COL_3,DatabaseHelper.COL_4};
    String where = param;
    Cursor c = db.query(true, DatabaseHelper.TABLE_NAME, COLS, DatabaseHelper.COL_2 + " = '" + where + "'", null, null, null, null, null);
    if(c != null){
        c.moveToFirst();
    }
    return c;
}

2 个解决方案

#1


2  

The most reliable way to get the most recent row in a table is to have a column defined in the table for the time of insert/update. Make sure this value is accurate at the time of insert/update, and create an index on it. You can then sort (descending) on this column to determine which one is the most recent - it will be the first row.

获取表中最近一行的最可靠方法是在插入/更新时在表中定义列。确保在插入/更新时这个值是准确的,并在其上创建一个索引。然后,您可以在这个列上排序(下降),以确定哪一个是最近的—它将是第一行。

#2


0  

As the automatically generated ID values increase with every insert, the row with the highest ID will be the one that was inserted most recently. So add an 'order by _id desc' and the first row will be the most recently inserted one.

随着自动生成的ID值随每次插入而增加,ID最高的行将是最近插入的行。因此,添加一个'order by _id desc',第一行将是最近插入的一行。

Note - this does not cover updates. If you need the row most recently inserted or updated, you'll have to use an additional timestamp column like Doug Stevenson suggested.

注意——这并不包括更新。如果您需要最近插入或更新的行,您将不得不使用像Doug Stevenson建议的额外的时间戳列。

#1


2  

The most reliable way to get the most recent row in a table is to have a column defined in the table for the time of insert/update. Make sure this value is accurate at the time of insert/update, and create an index on it. You can then sort (descending) on this column to determine which one is the most recent - it will be the first row.

获取表中最近一行的最可靠方法是在插入/更新时在表中定义列。确保在插入/更新时这个值是准确的,并在其上创建一个索引。然后,您可以在这个列上排序(下降),以确定哪一个是最近的—它将是第一行。

#2


0  

As the automatically generated ID values increase with every insert, the row with the highest ID will be the one that was inserted most recently. So add an 'order by _id desc' and the first row will be the most recently inserted one.

随着自动生成的ID值随每次插入而增加,ID最高的行将是最近插入的行。因此,添加一个'order by _id desc',第一行将是最近插入的一行。

Note - this does not cover updates. If you need the row most recently inserted or updated, you'll have to use an additional timestamp column like Doug Stevenson suggested.

注意——这并不包括更新。如果您需要最近插入或更新的行,您将不得不使用像Doug Stevenson建议的额外的时间戳列。