我想检查数据库中是否存在几个值。如果是,则如果游标为null,则该方法应返回TRUE或FALSE。但问题是尽管值不在数据库中,它仍会一直返回TRUE!我错过了什么?
// This method check if the combination image path and contact name already exists in database
public boolean checkContentDatabase(String imageFilePath, String contactName) {
String query = "Select * from " + DB_TABLE+ " where " + TABLE_IMAGE_PATH + "='" + imageFilePath + "' and " + TABLE_CONTACT_NAME + "='" + contactName +"' ;";
Cursor c = db.rawQuery(query, null);
if(c != null) // Exists in database
{
return true;
}
else
{
return false;
}
}
答案 0 :(得分:5)
将if条件替换为:
if(c.getCount() > 0)
{
return true;
}
else
{
return false;
}
答案 1 :(得分:3)
使用c != null && c.getCount() > 0
代替c != null
答案 2 :(得分:2)
public boolean checkContentDatabase(String imageFilePath, String contactName) {
String query = "Select * from " + DB_TABLE+ " where " + TABLE_IMAGE_PATH + "='" + imageFilePath + "' and " + TABLE_CONTACT_NAME + "='" + contactName +"' ;";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
if(c.isAfterLast() == false) {
return true;
}
else
{
return false;
}
}
答案 3 :(得分:1)
游标不为null,因为它已成功创建。只有您的结果集不存在。尝试使用“SELECT 1 FROM ...”,然后检查结果是否等于1.