在android中选择查询错误

时间:2017-08-08 12:24:05

标签: android mysql sqlite

我正在尝试使用id从数据库中获取值。但是它无法获取任何数据,它给出了语法错误。

这是我的选择功能

public Employee getStudentById(int Id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String selectQuery = "SELECT  " +
                Employee.KEY_ID + "," +
                Employee.KEY_name + "," +
                Employee.KEY_cast + "," +
                Employee.KEY_mobile +
                " FROM " + Employee.TABLE
                + " WHERE " +
                Employee.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string

        int iCount = 0;
        Employee student = new Employee();

        Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(Id)});

        if (cursor.moveToFirst()) {
            do {
                student.Employee_ID = cursor.getInt(cursor.getColumnIndex(Employee.KEY_ID));
                student.name = cursor.getString(cursor.getColumnIndex(Employee.KEY_name));
                student.cast = cursor.getString(cursor.getColumnIndex(Employee.KEY_cast));
                student.mobile = cursor.getInt(cursor.getColumnIndex(Employee.KEY_mobile));

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();
        return student;
    }

2 个答案:

答案 0 :(得分:1)

while compiling: SELECT id,name,cast,mobile FROM emp WHERE id=?

castsqlite keyword。您需要用双引号引用它:"cast"。或者更好的是,将列重命名为非关键字。

答案 1 :(得分:0)

你应该纠正声明这里

<强>语法

" WHERE " + Employee.KEY_ID + " = '"+ Id +"'";

您可以尝试使用

 String selectQuery = "SELECT  *  " FROM "+ Employee.TABLE + " WHERE " + Employee.KEY_ID + " = '"+ Id +"'";