簡體   English   中英

比較查詢SQLite數據庫返回的結果

[英]Comparing results returned by query SQLite database

我已經編寫了用於比較數據庫中用戶憑據的代碼。 首先,我檢查用戶名,然后根據返回的結果比較密碼。 如果兩者都匹配,我將打開另一個活動。 代碼對我來說似乎很好,但是我沒有數據庫方面的經驗,我可能在這里缺少一些關鍵的東西。 以下代碼由於某種原因無法正常工作。

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

我做錯了什么嗎?

問候

您應該增強您的方法,因為

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中的命名約定的信息。

我唯一看到的是您沒有關閉光標。

做這樣的事情:

Cursor c = null;
try {

    /* your stuff in here */

} finally {
    if (c != null) c.close();
}

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM