我构造了一段代码来搜索字符串值是否已存在于sqlite表中。这就是我所拥有的:
public boolean findvalue(String item) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor checkIfExist = db.rawQuery("SELECT * FROM "+ Table_item + " WHERE " + "itemName= " + "'" + item+ "'", null);
checkIfExist.moveToFirst();
if (checkIfExist.moveToFirst()){
return true;}
else{
return false;}
}
主要代码:
Store.setOnClickListener(
new View.OnClickListener() {
@Override public void onClick(View v) {
boolean s= myDatabase.findvalue(item.getText().toString());
if (s= true) {
Toast.makeText(createAcc.this, "item has been created", Toast.LENGTH_LONG).show();
}else if (exists = false) {
Toast.makeText(getBaseContext(), " " + Title.getText().toString() + " Exists", Toast.LENGTH_LONG).show();
}
}
}
);
即使表格中存在项目字符串值,它也总是给我真实的。任何想法可能是什么问题?
答案 0 :(得分:0)
1- if (s = true)
不正确,应为if (s==true)
2-它总是给我真实即使项目字符串值存在于当前代码应该执行此操作的表中,如果找到该值,它将返回true,检查s的条件应该是!,即if (s != true)
3-对于这种特殊情况,getCount()
可以更好地适应。
public boolean findvalue(String item) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor checkIfExist = db.rawQuery("SELECT * FROM "+ Table_item + " WHERE " + "itemName= " + "'" + item+ "'", null);
return checkIfExist.getCount()>0;
}
<强>附加强>
更好地利用rawQuery()
Cursor checkIfExist = db.rawQuery("SELECT * FROM "+ Table_item + " WHERE itemName= ?", new String[]{item});