2013-06-27 67 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; 
}