我在Android Studio上用SQL创建了一个数据库,但是无法恢复和更新该数据库中的数据。

我检查了很多网站和指南,但没有一个给我正确答案。

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table user(pseudo text primary key, password text, email text, points integer, pointsshop integer)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists user");
    }
    //inserting in database
    public boolean insert(String pseudo, String password, String email, int points, int pointsshop){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("pseudo",pseudo);
        contentValues.put("password",password);
        contentValues.put("email",email);
        contentValues.put("points",points);
        contentValues.put("pointsshop",pointsshop);
        long ins = db.insert("user",null,contentValues);
        if(ins==-1)return false;
        else return true;
    }

    public void update_points(int points, String pseudo){
            this.getWritableDatabase().execSQL("update user set
    points='" + points + "' where pseudo='" + pseudo + "'");
        }
        public int get_points(String pseudo){
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery("Select points from user where
            pseudo=?",new String[]{pseudo});
            return cursor.getInt(0);
        }
    }
}


我想从数据库中获取数据“点”,但是当我运行我的应用程序时,这崩溃了

最佳答案

尽管您已经提取了一个游标,但是游标在一个位于beforeFirstRow的位置,您需要移动到游标中的一行(如果有),然后才能检索数据。

完成操作后,应始终关闭游标。由于您不返回游标,因此应在返回从游标中提取的值之前将其关闭。

请尝试以下方法:

public int get_points(String pseudo) {
    int rv = -1;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("Select points from user where
    pseudo=?",new String[]{pseudo});
    if (cursor.moveToFirst()) {
        rv = cursor.getInt(cursor.getColumnIndex("points"));
    }
    cursor.close();
    return rv;
}



请注意,如果未提取任何数据,则以上将返回-1。此值可能不是一个有用的指示符,表明尚未提取任何数据,因此您可能需要使用其他值。
如果可以进行移动,则Cursor move方法(例如上面使用的moveToFirst)将返回true,否则返回false。因此if (cursor.moveToFirst())
已使用getColumnIndex,因为它不容易由于硬编码偏移量的错误计算而引入无意的错误。

关于java - 如何在Android Studio的SQL数据库中检索元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54598351/

10-08 22:33
查看更多