我知道有一个 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);
}
(db
是 SQLiteDatabase
的实例。)
我尝试了方法 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/