如何在SQLite Android中获取最后插入的行

5
我希望获取自动设置(AUTO INCREMENT)的最后一个插入行的主键值。我在S/O上搜索了最后一行ID的答案,但我需要最后一个插入行的值。请帮助我。
谢谢。

1
展示创建表的查询语句? - Rathan Kumar
你目前为止做了什么?一些代码将会更有帮助。 - Chintan Soni
1
可能是获取插入后生成的ID的重复问题。 - Gerald Schneider
https://dev59.com/vG035IYBdhLWcg3wc_sm#40962443 - Ahmad Aghazadeh
3个回答

19

尝试一下这段代码

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
第二个和第三个解决方案就是你所需要的。 - fmc

2

尝试这个:

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

或者

SELECT * FROM tablename ORDER BY row_id DESC LIMIT 1;

0

Cursor接口中使用moveToLast()

来自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
}

如果您想在插入数据时获取数据,可以在SQLiteDatabase中使用insert()
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));
}

这篇文章是关于自增的,如果你想阅读的话。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接