2017-08-08 60 views
0

我想從數據庫中獲取值使用id。但它不能獲取任何數據,它給我的語法錯誤。在android中選擇查詢錯誤

這是我的選擇功能

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; 
    } 
+1

你從哪裏得到錯誤?那是什麼錯誤?編譯時使用 –

+0

:SELECT id,name,cast,mobile FROM emp WHERE id =?在sqlite – Yogesh

+0

最新錯誤? –

回答

0

您應該及時糾正聲明這裏

語法

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

您可以

嘗試0
+1

Thanks @IntelliJ Amiya。此答案解決了我的問題 –

+0

我不明白這個答案正在解決什麼是語法問題。而是通過不使用'?'參數來改變查詢。 – laalto

+0

由於索引超出範圍,無法在索引1處綁定參數。該語句有0個參數。它給出了這個錯誤 – Yogesh

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

castsqlite keyword。您需要用雙引號引用它:"cast"。或者更好的是,將該列重命名爲不是關鍵字的內容。