moveToLast()
在Cursor
界面中使用。
来自android.googlesource.com
/**
* Move the cursor to the last row.
*
* <p>This method will return false if the cursor is empty.
*
* @return whether the move succeeded.
*/
boolean moveToLast();
简单的例子:
final static String TABLE_NAME = "table_name";
String name;
int id;
//....
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(cursor.moveToLast()){
//name = cursor.getString(column_index);//to get other values
id = cursor.getInt(0);//to get id, 0 is the column index
}
或者您可以在插入时获得最后一行(@GorgiRankovski 提到过):
long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred
他们还有多种方法可以使用查询来做到这一点:
- 一个由@DiegoTorresMilano 表示
SELECT MAX(id) FROM table_name
. 或获取所有列的值SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name)
。
- 如果您
PRiMARY KEY
已经坐到AUTOINCREMENT
,您可以SELECT
使用 max 到 min 并限制行数为 1 SELECT id FROM table ORDER BY column DESC LIMIT 1
(如果您想要每个值,请使用*
而不是id
)