我想檢查SQLite中的數據,如果已經存在可以更新或插入。我正在檢查這樣的代碼,我在下面提到。如何檢查SQLite中的數據如果已經存在更新或在Android中插入
代碼:
public long addmenus(String navigationdrawer,String optionname)
{
SQLiteDatabase menus=this.getWritableDatabase();
try {
ContentValues values=new ContentValues();
values.put(HEADER_NAME,navigationdrawer);
values.put(CHILD_NAME,optionname);
// menus.insert(TABLE_NAME,null,values);
// String owner=optionname;
Cursor cursor = menus.rawQuery("select * from TABLE_NAME where CHILD_NAME ='"+ optionname +"'", null);
if(cursor.getCount()<1)
{
//execute insert query here
long rows = menus.insert(TABLE_NAME, null, values);
return rows;
// return rows inserted.
}
else
{
//Perform the update query
String strFilter = "CHILD_NAME" + optionname;
long updaterow=menus.update(TABLE_NAME,values,strFilter,null);
return updaterow;
// return rows updated.
}
// menus.close();
} catch (Exception e) {
return -1;
}
finally {
if (menus != null)
menus.close();
}
}
我的活動:
我轉換整個JSON數據轉換爲字符串對象,然後插入到SQLite的。
String productpage=jsonObject.toString();
db.addmenus(productpage,"Navigationmenus");
但它不工作,它不能插入到sqlite中。
任何人都可以解決這個問題很高興欣賞。 在此先感謝
你得到了什麼錯誤?此外,它看起來像使用'TABLE_NAME'和'CHILD_NAME'作爲字符串,而不是它們似乎是常量。 – Nathanael
表名是我的表名,並有兩個列子名稱和標題名稱。我必須將整個json數據轉換爲字符串插入到列標題名稱,我會給一個選項名稱例如。菜單爲一個JSON然後第二個產品選項爲另一個JSON – Nivethitha
您正在存儲JSON到Sqlite?你可能想看看使用Realm作爲你的數據庫,而不是 –