简体   繁体   中英

Comparing results returned by query SQLite database

I have written code for comparing user credentials in database. First I check the username and then based on the returned results, I compare the password. If both match, I open another activity. The code seems fine to me, but I have no experience in database stuff, I might be missing somehthing crucial here. The following code is not working for some reason.

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

Is there anything I am doing wrong?

Regards

You should enhance your method as

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

And yes you should read about naming convention in java or Android.

The only thing I see, is that you don't close the cursor.

Do something like so:

Cursor c = null;
try {

    /* your stuff in here */

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

This should work in the way you want.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM