2013-06-27 65 views
0

我已經編寫了用於比較數據庫中的用戶憑據的代碼。首先我檢查用戶名,然後根據返回的結果,我比較密碼。如果兩者都匹配,我打開另一個活動。代碼對我來說似乎很好,但我對數據庫的東西沒有經驗,我可能會在這裏失去一些至關重要的東西。以下代碼由於某種原因而不起作用。比較查詢SQLite數據庫返回的結果

public boolean Compare(String username, String pass) 
{ 
    Cursor c = sqlDB.query(DB_NAME, columns, DB_COL_EMAIL + "='" + username+ "'", null, null, null, null); 



    if(c!=null && c.getCount()>0) 
    { 
     Toast.makeText(context, "inside check", Toast.LENGTH_SHORT).show(); 
     c.moveToFirst(); 

     int passwordCol_number= c.getColumnIndex(DB_COL_PASS); 
     boolean found = false; 

     while(c.moveToNext()) 

     { 
      found = pass.equals(c.getString(passwordCol_number)); 

      if(found) 
       return true; 
     } 
    } 
return false; 
} 

有什麼我做錯了嗎?

Regards

+0

後,你得到這樣我們就可以明白什麼是你遇到 – 7bluephoenix

+1

這裏不回答你的問題的錯誤,但你真的真的應該閱讀有關SQL注入和密碼哈希的'logcat'跟蹤;)(和也是java命名約定) – Guillaume

回答

1

你應該提高你的方法

public boolean compareLogin(String username, String pass) { 
    String where = DB_COL_EMAIL + " = ? AND " + DB_COL_PASS + " = ?"; 
    String[] whereParams = new String[]{username, pass}; 

    Cursor mCursor = db.query(DB_NAME, columns, 
      where, 
      whereParams, 
      null, 
      null, 
       null); 

    if (mCursor != null && mCursor.moveToFirst()) 
     return true; 
    else 
     return false; 
} 

是的,你應該閱讀有關使用Java或Android命名約定。

+0

這是什麼「=?AND」呢?你可以詳細說明一下 – user2498079

+0

'哪裏''String'有'''實際值的位置,實際值作爲'String []'和'whereParams'參數傳入。 SQLite將用'String []''whereParams'中的值替換這些'?'。 –

+0

你有沒有得到你的答案? –

0

我唯一看到的是你不關閉遊標。

做類似這樣:

0

這應該以您想要的方式工作。

public boolean Compare(String username, String pass) { 
    Cursor c = sqlDB.query(DB_NAME, columns, DB_COL_EMAIL + "='" + username+ "'", null, null, null, null); 

    // No need to check c != null and c.getCount() 
    // c will not be null even if no rows returned. 

    boolean found = false; 
    // c.moveToFirst() will return false if no rows returned 
    // so this line should be sufficient 
    if (c.moveToFirst()) { 
     // while (c.moveToNext()) should be commented 
     // remember you just called moveToFirst()? 
     // moveToNext() will move to next row 
     // and will returned false if no more rows in the cursor 

     found = pass.equals(c.getString(passwordCol_number)); 
    } 
    c.close(); 
    return found; 
}