java - SQLite 数据库 : Insert only if the value does not exist (not via raw SQL command)

标签 java android android-sqlite sql-insert

我知道有一个 SQL 命令是这样的:IF NOT EXISTS,但是由于 Android 的 SQLiteDatabase 类有一些很好的方法,我想知道是否可以插入一个值,如果它不存在通过一个方法。

目前我正在使用它来插入一个String:

public long insertString(String key, String value) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(key, value);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

(dbSQLiteDatabase 的实例。)

我尝试了方法 insertOrThrow() 而不是 insert(),但它似乎与 insert() 的作用相同。也就是说,如果该值已在行中,则会再次插入,因此该行现在有两个值相同的值。

最佳答案

SQLiteDatabase: Insert only if the value does not exist (not via raw SQL command)

因为您不想使用原始查询,您可以在插入之前实现它,只需创建一些函数来测试值是否已经在数据库中。它可以返回 boolean(或 int),如果返回 false,您将执行插入查询。

一个小例子:

public int getCount() {
    Cursor c = null;
    try {
        db = Dbhelper.getReadableDatabase();
        String query = "select count(*) from TableName where name = ?";
        c = db.rawQuery(query, new String[] {name});
        if (c.moveToFirst()) {
            return c.getInt(0);
        }
        return 0;
    }
    finally {
        if (c != null) {
            c.close();
        }
        if (db != null) {
            db.close();
        }
    }
}

if (getCount() == 0) {
   //perform inserting
}

if the value is already in the row, it's inserted again so the row now has two values of the same value.

这可以通过使用不允许插入重复项的适当约束来解决。检查这个:

关于java - SQLite 数据库 : Insert only if the value does not exist (not via raw SQL command),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15707796/

相关文章:

java - 缺少返回语句编译错误

java - Gradle bootrun 错误,进程命令以非零退出值 1 完成

android - 需要有关设置网络系统以更新同一网络上的多个设备的指导

angular - SQLite 与 ionic 4?无法读取未定义类型错误 : Cannot read property 'then' of undefined 的属性 'then'

android - java.lang.IllegalStateException : attempt to re-open an already-closed object(Tried closing )

java - FHIR迁移和向后兼容性

java - JUnit 测试失败

android - 使用自动完成时 TextInputLayout 背景颜色发生变化

android - 有没有办法可以从Linux终端下载Sdk命令行工具?