Android工作室SQLite主键未返回

我有一个名为student的表使用SQLite,我试图使用SELECT查询获取一个学生的id,有我的方法:

public int getID(String name, String surname){
    int id;
    String selectQuery = "SELECT* FROM " + TABLE_NAME + " WHERE " + COL_2 + " =\"" + name + "\" AND " + COL_3 + " =\"" + surname + "\";";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery,null); //App is crashing here
    id = cursor.getInt(0);
    return id;
}

我将数据插入数据库的代码:

public boolean insertStudent(String name, String surname){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2, name);
    contentValues.put(COL_3, surname);
    long result=db.insert(TABLE_NAME,null,contentValues);
    if(result == -1)
        return false;
    else
        return true;
}

然后创建查询表:

@Override
public void onCreate(SQLiteDatabase db){
    //Requête SQL de la création de la table student
    db.execSQL("CREATE table " + TABLE_NAME + "(student_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, surname TEXT)");

应用程序崩溃在db.rawQuery(selectQuery,null);,我不知道为什么 . 我试图手动插入id,用自动增量整数,不工作,所以,我不知道,等着你帮我,谢谢

回答(3)

2 years ago

当你试图从第一行之前的位置提取数据时,我怀疑崩溃实际上是在下一行 .

我建议尝试: -

public int getID(String name, String surname){
    int id = -1;
    String selectQuery = "SELECT* FROM " + TABLE_NAME + " WHERE " + COL_2 + " =\"" + name + "\" AND " + COL_3 + " =\"" + surname + "\";";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery,null); //App is crashing here
    if (cursor.moveToFirst) {
        id = cursor.getInt(0);
    }
    return id;
}

也就是说,如果Cursor不为空,那么您将移动到第一行并从实际行中提取数据 . 如果Cursor为空,则返回-1 .

2 years ago

SQL中的字符串在 'single quotes' 中 . "double quoted strings" 被视为标识符,您会收到有关它们的语法错误,因为这些名称没有列 .

为了避免引用和避免SQL注入的需要,最好将SQL参数作为变量提供,如:

String selectQuery = "SELECT* FROM " + TABLE_NAME + " WHERE " + COL_2 + " =? AND " + COL_3 + " =?;";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[] { name, surname });

修复此问题后,您将崩溃,MikeT突出显示无效的光标位置问题 .

2 years ago

撞车是什么意思?堆栈跟踪会很有帮助 .

无论如何,除了别人提到的内容之外,你的SQL中还有一个拼写错误:

"SELECT* FROM "

我假设你需要一个空格*:

"SELECT * FROM "