我在SQLite
中创建了一个表,我想在用户可以将该值添加到表之前检查该值是否存在。请检查下面的代码:
//check if value exists
Cursor checkIfExist = shoppingListDB.rawQuery("SELECT * FROM "+ selected_spinner + " WHERE " + "ITEM_NAME = " + "'" + add_tems + "'", null);
if (checkIfExist == null) {
String insert_data="INSERT INTO " + selected_spinner + " (ITEM_NAME,SHOP_LIST,NUMB_ITEMS) VALUES " + "('" + add_tems + "'," + "'" + add_shop + "'," + "'" + add_quantity + "'" + ")";
shoppingListDB.execSQL(insert_data);
} else
Toast.makeText(getBaseContext(), " " + add_tems + " Exists", Toast.LENGTH_LONG).show();
答案 0 :(得分:0)
试试这种方式,
Cursor checkIfExist = shoppingListDB.rawQuery("SELECT * FROM "+ selected_spinner + " WHERE " + "ITEM_NAME = " + "'" + add_tems + "'", null);
checkIfExist.moveToFirst();
if ( checkIfExist.getCount() > 0 )
{
String insert_data="INSERT INTO " + selected_spinner + " (ITEM_NAME,SHOP_LIST,NUMB_ITEMS) VALUES " + "('" + add_tems + "'," + "'" + add_shop + "'," + "'" + add_quantity + "'" + ")";
shoppingListDB.execSQL(insert_data);
}
else
{
Toast.makeText(getBaseContext(), " " + add_tems + " Exists", Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
执行else子句是因为Cursor对象永远不会为null。 rawQuery()总是返回一个Cursor对象。 因此,您需要测试sql查询是否影响了一行或多行:
if(checkIfExist.moveToFirst()){
//value exist
}else{
//value does not exist
}
如果Cursor为空(doc),moveToFirst()将返回false
答案 2 :(得分:0)
这是一个实施问题。您可以更改方法,以使用List
Database
类似的东西:
public List<Item> getAllItems() {
List<Item> items = new LinkedList<Item>();
// 1. build the query
String query = "SELECT * FROM " + selected_spinner;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build item and add it to list
Item item = null;
if (cursor.moveToFirst()) {
do {
item = new Item ((cursor.getString(1)), cursor.getString(2));
item .setId(Integer.parseInt(cursor.getString(0)));
// Add item to items
items.add(item);
} while (cursor.moveToNext());
}
Log.d("getAllItems()", items.toString());
// return items
return items;
}
然后,您可以调用该方法:
boolean valueExist = false;
private List<String> nameOfItems = new ArrayList<String>();
private static List<Item> itemList = null;
DataBaseHelper db = new DataBaseHelper(this);
itemList = db.getAllItems();
db.close();
if(itemList .size() != 0){
for(Item i : itemList ){
nameOfItems .add(i.getName());
}
}
最后检查值是否存在......
if(nameOfItems.contains(//Any String that you might want to check){
valueExist = true;
}