[英]Android : SQLite check if data exist and update
I now sure what i'm doing wrong because java and SQLite for me new. 我现在确定我做错了,因为java和SQLite对我来说是新的。 So I need to make check when user is entering new data to DB if data with such "day" and "week_type" exists it need to be updated , else create new row.
因此,当用户正在向DB输入新数据时,如果需要更新带有“ day”和“ week_type”的数据,则需要进行检查,否则需要创建新行。
public long creatEntry(int day2, int week_type2,
String desc2, String place2, String lessnum2) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues() ;
String update = "SELECT * FROM info WHERE day="+day2+" AND week_type="+week_type;
Cursor cr = ourDatabase.rawQuery(update, null);
if(cr!= null){
cv.put(day, day2);
cv.put(week_type, week_type2);
cv.put(desc, desc2);
cv.put(place, place2);
cv.put(lessnum, lessnum2);
return ourDatabase.update(DATABASE_TABLE,cv, day+ "=" +day2+ " AND "+week_type+ "=" +week_type2, null);
}
else{
cv.put(day, day2);
cv.put(week_type, week_type2);
cv.put(desc, desc2);
cv.put(place, place2);
cv.put(lessnum, lessnum2);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
}
Use replace. 使用替换。 It'll try to insert first, and if it happens to conflict due to a key constraint, it'll delete and insert those values.
它将尝试首先插入,如果由于键约束而发生冲突,它将删除并插入这些值。 In your case, these two columns must be unique .
在您的情况下,这两列必须是唯一的 。 Check it out:
看看这个:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace(java.lang.String, java.lang.String, android.content.ContentValues) http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace(java.lang.String,java.lang.String,android.content.ContentValues)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.