我在我的SQLite数据库中有一个表,它由几个int组成,我想在添加新行之前检查一对是否已存在。
我有这个function从表TableName(id1,id2)返回数据:
public Cursor getIds() {
return db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
}
在另一堂课中,我有这些:
int int1 = 14
int int2 = 2564
if (????) {
m.addToTable(int1, int2);
} else {
//Datas already exists
}
我需要做什么来比较int1与列id1和int2的值与列id2的值?
分析解答
创建此方法:
public boolean existIds(int id1, int id2) {
Cursor c = db.rawQuery(
"SELECT * FROM " + TABLE_NAME + " WHERE id1 = ? AND id2 = ?",
new String[]{String.valueOf(id1), String.valueOf(id2)}
);
boolean result = c.getCount() > 0;
c.close();
return result;
}
现在您可以在代码中使用它:
int int1 = 14
int int2 = 2564
if (!existIds(int1, int2)) {
m.addToTable(int1, int2);
} else {
//do something because the ids already exist
}