简体   繁体   中英

Android : SQLite check if data exist and update

I now sure what i'm doing wrong because java and SQLite for me new. 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.

                    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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM