【发布时间】:2017-09-29 00:16:20
【问题描述】:
我找到了一些关于创建本地 SQL 数据库的教程。
我需要更新我的数据库的值,或者如果它不存在,则将其插入到表中。
我认为我可以使用“更新”的 IF 语句和布尔属性。
public void onClick(View view) {
if (view == play) {
//Here I am trying to update position one with the value of (int) test
boolean uc = myDb.AggiornaStato("1",test);
//If the field is empty bool should be false, right?
if (uc == false) {
//so .. insert that value
myDb.CreaStato(test);
}
//next time, update should be true, and It won't create another ID
startService(new Intent(this, t1.class));
}
我必须管理七个 ID,因此我将为每个 ID 和每一行创建不同的方法。我知道这不是正确的方法,但我找不到适合我需要的东西。当应用程序启动时,它会创建空的数据库和表,因此我第一次需要插入值,但随后我只需要更新,我想我可以使用“If then else”,但我在某个地方搞砸了!
这是我在 databaseHelper 类中创建(CreaStato)或更新(Aggiorna Stato)的内容
public boolean CreaStato(int stato) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_6, stato);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean AggiornaStato (String id, int stato) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_6, stato);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
【问题讨论】:
-
I need to update a value of my database or insert it in the table if it does not already exists.只需使用REPLACE INTO而不是INSERT INTOSQL 命令。在你的情况下:db.replace(). -
这条评论有点不相关,但你看过 Realm。 realm.io 这是一款快速且非常易于使用的数据库工具,适用于包括安卓在内的所有平台。它非常容易实现,对于像您这样的初学者来说,它是完美的。
-
非常感谢Rotwang! :-) 有效!我必须改变一些东西才能让它正常工作。我删除了“自动增量”并将 ID 添加到“替换”方法中!
标签: android sql sqlite boolean sql-insert