【问题标题】:getting id of a username in SQLite database Android在 SQLite 数据库 Android 中获取用户名的 id
【发布时间】:2021-04-25 09:19:44
【问题描述】:

在我的 android 应用程序中,如何编辑此代码以返回用户名的 id?(我使用的是 SQLite 数据库)

    public int GetId(String username){
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT id FROM user WHERE username=?", new String[]{username});
        return id;

【问题讨论】:

    标签: java android database sqlite android-sqlite


    【解决方案1】:

    在你得到光标后:

    Cursor cursor = sqLiteDatabase.rawQuery("SELECT id FROM user WHERE username=?", new String[]{username});
    

    您必须将光标的索引移动到其第一行(如果用户存在于表中)并读取id

    public int GetId(String username) {
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT id FROM user WHERE username=?", new String[]{username});
        int id = -1;
        if (cursor.moveToFirst()) id = cursor.getInt(0);
        cursor.close();
        sqLiteDatabase.close();
        return id;
    }
    

    如果未找到用户,GetId() 方法将返回 -1,因此您可以检查此值以确定 username 是否属于现有用户。

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 2017-06-23
      相关资源
      最近更新 更多