gpt4 book ai didi

java - 如何在 Android Studio 上检索 SQL 数据库中的元素?

转载 作者:行者123 更新时间:2023-11-30 10:06:35 25 4
gpt4 key购买 nike

我在 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);
}
}
}

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

最佳答案

虽然您已经提取了一个 Cursor,但光标位于一个名为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com