如何在SQlite android中获取最后一行

时间:2015-06-23 05:57:21

标签: android android-sqlite

我想获得最后插入的行的自动设置的主键值(AUTO INCREMENT)。我搜索了S / O并找到了最后一行row_id的答案。但我需要最后插入的行的值。请帮帮我。

由于

3 个答案:

答案 0 :(得分:8)

试试此代码

String selectQuery = "SELECT  * FROM " + "sqlite_sequence";
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToLast();

SELECT * 
FROM    TABLE
WHERE   ID = (SELECT MAX(ID)  FROM TABLE);

SELECT * FROM table ORDER BY column DESC LIMIT 1;

答案 1 :(得分:2)

试试这个:

select * from <TABLE> where row_id = (select max(row_id) from <TABLE>);

SELECT * FROM tablename ORDER BY row_id DESC LIMIT 1;

答案 2 :(得分:0)

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;
//....

Cursor cursor = db.rawQuery("SELECT  * FROM " + TABLE_NAME, null);

if(cursor.moveToLast()){
    name = cursor.getString(column_index);
    //--get other cols values
}

如果您想在插入时获取数据,可以在insert()中使用SQLiteDatabase class

private static final String TABLE_NAME = "table_name";
private static final String COLUMN_ONE = "ID";
private static final String COLUMN_TWO = "NAME";

long row = 0;//to get last row
//.....
SQLiteDatabase db= this.getWritableDatabase();

ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_TWO, name);//name is a variable for data value

row = db.insert(TABLE_NAME, null, contentValues);
//insert() returns the row ID of the newly inserted row, or -1 if an error occurred 

Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE ID = ?", new String[] { row+"" });
while (res.moveToNext()) {//there is no need to use while, if condition is good.
    System.out.println(res.getString(0));//I just sout to avoid more code.
    System.out.println(res.getString(1));
}

This is post is about autoincrement, if you want to read.