2

我现在确定我做错了什么,因为 java 和 SQLite 对我来说是新的。所以我需要检查用户何时向数据库输入新数据,如果存在这样的“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);
            }
        }
4

1 回答 1

0

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

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

于 2012-12-05T17:35:52.310 回答