eig*_*tx2 15 java android sql-insert android-sqlite
我知道有一个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);
}
Run Code Online (Sandbox Code Playgroud)
(db是.的一个例子SQLiteDatabase.)
我尝试了这种方法insertOrThrow()而不是insert(),但它看起来和它一样insert().也就是说,如果该值已经在行中,则会再次插入该值,因此该行现在具有两个相同值的值.
Sim*_*iak 16
SQLiteDatabase:仅在值不存在时插入(不通过原始SQL命令)
由于您不想使用原始查询,因此您可以在插入之前实现它,只需创建一些函数来测试值是否已存在于数据库中.它可以返回boolean(或int),如果返回false,则执行insert查询.
一个小例子:
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
}
Run Code Online (Sandbox Code Playgroud)
如果该值已经在行中,则会再次插入,因此该行现在具有两个相同值的值.
这可以通过使用适当的约束来解决,这些约束不允许您插入重复项.检查一下:
new*_*rld 13
您可以为插入行的冲突设置CONFLICT_IGNORE行为:
public long insertString(String key, String value) {
ContentValues initialValues = new ContentValues();
initialValues.put(key, value);
return db.insertWithOnConflict(DATABASE_TABLE, null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);
}
Run Code Online (Sandbox Code Playgroud)
但这取决于约束.如果您将来需要,还有更多行为.