2011-04-28 113 views
9

我想在android sqlite中通過id獲得一個特定的行,並且寫了下面的代碼,但它不返回任何記錄。我寫了一個getAllRecords()方法,它返回數據庫中的所有記錄。Android在Sqlite中通過Id選擇行?

任何人都可以解釋我犯的錯誤嗎?

public Bank getBankById(int bankId) 
    { 

     Cursor cursor=null; 
     Bank bnk = null; 
     cursor = this.db.rawQuery("select * from " + BanksTable.NAME + " where " + BanksTable.COL_ID + "=" + bankId , null); 
     if (cursor != null) 
      { 
      if (cursor.moveToFirst()) 
       { 
      int id = cursor.getInt(cursor.getColumnIndex(BanksTable.COL_ID)); 
      String name = cursor.getString(cursor.getColumnIndex(BanksTable.COL_NAME)); 
      String url = cursor.getString(cursor.getColumnIndex(BanksTable.COL_IMAGE_URL)); 
      byte[] image = cursor.getBlob(cursor.getColumnIndex(BanksTable.COL_IMAGE)); 
      bnk=new Bank(); 
      bnk.setId(id); 
      bnk.setImageURL(url); 
      bnk.setName(name); 
      bnk.setImageByteArray(image); 
       } 
      cursor.close(); 
      } 
     return bnk; 

    } 
+0

當你得到你的logcat的任何異常加入「自動增量」屬性ID,解決這個問題? – 2011-04-28 10:30:20

+0

其中是BanksTable.COL_ID和表定義? – Selvin 2011-04-28 10:31:16

+0

db.execSQL( 「CREATE TABLE IF NOT EXISTS」 + BanksTable.NAME + 「( 」 \t \t \t \t + BanksTable.COL_ID +「 整數PRIMARY KEY, 」+ \t \t \t \t BanksTable.COL_NAME +「 VARCHAR」 + \t \t \t \t BanksTable.COL_IMAGE_URL + 「VARCHAR」 + \t \t \t \t BanksTable.COL_IMAGE + 「BLOB);」); – UMAR 2011-04-28 11:03:59

回答

9

我結束了這個問題,通過改變參數到名稱。 它的奇怪,但我仍然不知道爲什麼它不工作。

我得到的銀行ID像0,1,2,3,4可能是不允許在sqlite或內部影響它,但我仍然不確定。

cursor = this.db.rawQuery("select * from " + BanksTable.NAME + " where " + BanksTable.COL_NAME + "='" + bankName + "'" , null); 
+1

或使用trim()方法插入/獲取記錄。 – UMAR 2011-05-25 12:04:40

0

我通過創建表

db.execSQL("CREATE TABLE IF NOT EXISTS " + BanksTable.NAME +" (" +BanksTable.COL_ID + " 
integer PRIMARY KEY **autoincrement**, "+ BanksTable.COL_NAME + " varchar, " + 
BanksTable.COL_IMAGE_URL + " varchar," + BanksTable.COL_IMAGE + " blob);");