0

我编写了用于比较数据库中用户凭据的代码。首先我检查用户名,然后根据返回的结果比较密码。如果两者都匹配,我打开另一个活动。代码对我来说似乎很好,但我没有数据库方面的经验,我可能在这里遗漏了一些重要的东西。以下代码由于某种原因无法正常工作。

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

有什么我做错了吗?

问候

4

3 回答 3

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 中的命名约定。

于 2013-06-27T10:42:49.460 回答
0

我唯一看到的是你没有关闭光标。

做这样的事情:

Cursor c = null;
try {

    /* your stuff in here */

} finally {
    if (c != null) c.close();
}
于 2013-06-27T10:36:01.593 回答
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;
}
于 2013-06-27T10:44:04.827 回答