【问题标题】:SQLite Update and bool resultsSQLite 更新和布尔结果
【发布时间】: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 INTO SQL 命令。在你的情况下:db.replace().
  • 这条评论有点不相关,但你看过 Realm。 realm.io 这是一款快速且非常易于使用的数据库工具,适用于包括安卓在内的所有平台。它非常容易实现,对于像您这样的初学者来说,它是完美的。
  • 非常感谢Rotwang! :-) 有效!我必须改变一些东西才能让它正常工作。我删除了“自动增量”并将 ID 添加到“替换”方法中!

标签: android sql sqlite boolean sql-insert


【解决方案1】:

您的AggiornaStato() 函数始终返回true

update() function 返回实际更新的行数,因此您必须检查:

public boolean AggiornaStato (String id, int stato) {
    ...
    int rows = db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{ id });
    return rows > 0;
}

public void onClick(View view) {
    ...
    boolean updated = myDb.AggiornaStato("1", test);
    if (!updated)
        myDb.CreaStato(test);
    ...
}

(最好将insert() 替换为insertOrThrow()。)

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 2015-06-17
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多