我希望获取自动设置(AUTO INCREMENT)的最后一个插入行的主键值。我在S/O上搜索了最后一行ID的答案,但我需要最后一个插入行的值。请帮助我。
谢谢。
谢谢。
尝试一下这段代码
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;
尝试这个:
select * from <TABLE> where row_id = (select max(row_id) from <TABLE>);
或者
SELECT * FROM tablename ORDER BY row_id DESC LIMIT 1;
在Cursor
接口中使用moveToLast()
。
/**
* 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));
}