Android:SQLite检查数据是否存在并更新

时间:2012-12-05 17:31:50

标签: java android sqlite sql-update

我现在确定我做错了什么因为java和SQLite对我而言是新的。因此,如果存在需要更新的“day”和“week_type”的数据,我需要检查用户何时向DB输入新数据,否则需要更新,否则创建新行。

                    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);
            }
        }

1 个答案:

答案 0 :(得分:0)

使用替换。它将首先尝试插入,如果由于键约束而发生冲突,它将删除并插入这些值。在您的情况下,这两列必须是unique。看看:

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace(java.lang.String, java.lang.String, android.content.ContentValues)