从 SQLite 数据库 Android 获取最后插入的值

发布于 2024-09-29 18:39:06 字数 295 浏览 4 评论 0原文

我正在尝试从 Android 中的 sqlite 数据库获取最后插入的 rowid。我读过很多关于它的帖子,但无法让其中一个工作。 这是我的方法:

 public Cursor getLastId() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}

我尝试过使用MAX,但我一定是用错了。还有别的办法吗?

I am trying to get the last inserted rowid from a sqlite database in Android. I have read a lot of posts about it, but can't get one to work.
This is my method:

 public Cursor getLastId() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_WID}, KEY_WID + "=" + MAX(_id), null, null, null, null, null);}

I have tried with MAX, but I must be using it wrong. Is there another way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

殤城〤 2024-10-06 18:39:06

实际上 SQLiteDatabase 类有它自己的 insert 方法,它返回新创建的行的 id。我认为这是获得新身份证的最佳方式。
您可以查看其文档此处

我希望这有帮助。

Well actually the SQLiteDatabase class has its own insert method which returns the id of the newly created row. I think this is the best way to get the new ID.
You can check its documentation here.

I hope this helps.

东走西顾 2024-10-06 18:39:06

用于

 SELECT last_insert_rowid();

获取最后插入的rowid。
如果您使用 AUTOINCRMENT 关键字,则会

SELECT * from SQLITE_SEQUENCE;

告诉您每个表的值。

Use

 SELECT last_insert_rowid();

to get the last inserted rowid.
If you are using AUTOINCREMENT keyword then

SELECT * from SQLITE_SEQUENCE;

will tell you the values for every table.

愛上了 2024-10-06 18:39:06

要从表中获取最后一行..

Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();

To get the last row from the table..

Cursor cursor = theDatabase.query(DATABASE_TABLE, columns,null, null, null, null, null);
cursor.moveToLast();
秋叶绚丽 2024-10-06 18:39:06

使用 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;
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 

此外,您还可以使用查询来执行此操作的多种方式:

  1. 表示
  2. 其中一种由 @DiegoTorresMilano 从表名中选择 MAX(id)。或者获取所有列值SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name)
  3. 如果您的 PRiMARY KEY 已设置为 AUTOINCRMENT,您可以 SELECT 值从最大值到最小值,并使用 SELECT 将行数限制为 1 id FROM 表 ORDER BY 列 DESC LIMIT 1
    (如果您想要每个值,请使用 * 而不是 id

Use moveToLast() in Cursor interface.

From 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();

Simple example:

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
}

Or you can get the last row when insertion(Which is @GorgiRankovski have mentioned):

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 

Also their is a multiple ways you can do this using query:

  1. One is expressed by @DiegoTorresMilano
  2. SELECT MAX(id) FROM table_name. or to get all columns values SELECT * FROM table_name WHERE id = (SELECT MAX(id) FROM table_name).
  3. If your PRiMARY KEY have sat to AUTOINCREMENT, you can SELECT vaules occording to max to min and limit the rows to 1 using SELECT id FROM table ORDER BY column DESC LIMIT 1
    (If you want each and every value, use * instead of id)
抱猫软卧 2024-10-06 18:39:06

如果您想要插入后的last_insert_id,您可以使用它:

public long insert(String table, String[] fields, String[] vals ) 
{
    String nullColumnHack = null;
    ContentValues values = new ContentValues();
    for (int i = 0; i < fields.length; i++) 
    {
        values.put(fields[i], vals[i]); 
    }

    return myDataBase.insert(table, nullColumnHack, values);
}

If you want the last_insert_id just afert a insert you can use that :

public long insert(String table, String[] fields, String[] vals ) 
{
    String nullColumnHack = null;
    ContentValues values = new ContentValues();
    for (int i = 0; i < fields.length; i++) 
    {
        values.put(fields[i], vals[i]); 
    }

    return myDataBase.insert(table, nullColumnHack, values);
}
扛刀软妹 2024-10-06 18:39:06

insert 方法返回刚刚插入的行的 id,如果插入过程中出现错误,则返回 -1。

long id = db.insert("your insertion statement");

db 是 SQLiteDatabase 的一个实例。

The insert method returns the id of row just inserted or -1 if there was an error during insertion.

long id = db.insert("your insertion statement");

db is an instance of your SQLiteDatabase.

哆啦不做梦 2024-10-06 18:39:06

试试这个:

public Cursor getLastId() {
        return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}

Try this:

public Cursor getLastId() {
        return mDb.query(DATABASE_TABLE, new String[] { **MAX(id)** }, null, null, null, null, null, null);}
北方的韩爷 2024-10-06 18:39:06
/**
 * @return
 */
public long getLastInsertId() {
    long index = 0;
    SQLiteDatabase sdb = getReadableDatabase();
    Cursor cursor = sdb.query(
            "sqlite_sequence",
            new String[]{"seq"},
            "name = ?",
            new String[]{TABLENAME},
            null,
            null,
            null,
            null
    );
    if (cursor.moveToFirst()) {
        index = cursor.getLong(cursor.getColumnIndex("seq"));
    }
    cursor.close();
    return index;
}
/**
 * @return
 */
public long getLastInsertId() {
    long index = 0;
    SQLiteDatabase sdb = getReadableDatabase();
    Cursor cursor = sdb.query(
            "sqlite_sequence",
            new String[]{"seq"},
            "name = ?",
            new String[]{TABLENAME},
            null,
            null,
            null,
            null
    );
    if (cursor.moveToFirst()) {
        index = cursor.getLong(cursor.getColumnIndex("seq"));
    }
    cursor.close();
    return index;
}
怀里藏娇 2024-10-06 18:39:06

我用这个

public int lastId(){
    SQLiteDatabase db =  
  this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from resep", null );
    res.moveToLast();
    return res.getInt(0);
}

I use this

public int lastId(){
    SQLiteDatabase db =  
  this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from resep", null );
    res.moveToLast();
    return res.getInt(0);
}
天气好吗我好吗 2024-10-06 18:39:06

在您的 DbHelper 类中,

    public long getLastIdFromMyTable()
    {
        SQLiteDatabase db = this.getReadableDatabase();
        SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
        return st.simpleQueryForLong();
    }

In your DbHelper class,

    public long getLastIdFromMyTable()
    {
        SQLiteDatabase db = this.getReadableDatabase();
        SQLiteStatement st = db.compileStatement("SELECT last_insert_rowid() from " + MY_TABLE);
        return st.simpleQueryForLong();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文