SQLite,获取表中的最后一项 [英] SQLite, getting last item in table

查看:69
本文介绍了SQLite,获取表中的最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助来使用我创建的数据库.我需要访问数据库中的最后一项.这是我获取单个项目的代码.如何将其更改为仅获取最后一个?

I need some help with using the database that I created. I need to access the last item in the database. This is my code that gets a single item. How can I change it to only get the last?

// Getting single user
User getuser(int id) {
    SQLiteDatabase db = this.getReadableDatabase();


    Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
            KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT, 
            KEY_GOAL, KEY_BMI }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);

    if(cursor!=null && cursor.getCount()!=0){
          cursor.moveToFirst();
    }

    User user = new User(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4), 
            cursor.getString(5), cursor.getFloat(6));
    return user;
}

推荐答案

如果 id 唯一标识用户,那么您将只得到一行作为您传递的 id 的结果,因此您不必担心它是数据库中的最后一个或第一个.如果只是想要数据库中的最后一行,那么您不必传递 id,您可以执行 select * 并在检索后将光标移至最后一行,即 cursor.moveToLast().

if the id uniquely identifies the user then you will be getting only one row as the result for the id you are passing so you dont have to worry about it is the last or first in the database. if it is just that you want the last row in your database then you dont have to pass an id you can do a select * and after retrieving move the cursor to last ie cursor.moveToLast().

如果您只想要最后一行,请执行此操作

Do this if you just want the last row

User getuser() {
  SQLiteDatabase db = this.getReadableDatabase();


  Cursor cursor = db.query(TABLE_USER, new String[] { KEY_ID,
        KEY_NAME, KEY_AGE, KEY_WEIGHT, KEY_HEIGHT, 
        KEY_GOAL, KEY_BMI }, null,
        null, null, null, null, null);

  if(cursor!=null && cursor.getCount()!=0){
      cursor.moveToLast();
  }

  User user = new User(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1), cursor.getInt(2),cursor.getInt(3), cursor.getInt(4), 
        cursor.getString(5), cursor.getFloat(6));
  return user;
}

你的电话可以是这样

User currentUser = db.getUser();

如果您传递一个 id 来获取用户详细信息,该 id 唯一标识用户,那么您所做的将起作用

If you are passing an id to get a user details an the id uniquely identifies the user then what you have done will work

这篇关于SQLite,获取表中的最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆