[英]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. 是的,您应该阅读有关Java或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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.