Add database entry if not exists

时间:2015-06-25 18:46:24

标签: java android sqlite

I'm stuck with a logical problem. I have an SQLite table with the fields id, markerID (String) and score (Integer). Now I want to look if there is already an entry for a certain markerID and if not add a Score. If the stored Score is less than 5 I want to do nothing and if not I want to update the Score of the particular entry. Now I have the problem, that the cursor goes through all entries and adds an entry if there is already an entry with other markerID, even if related to the current markerID it should do nothing. So it runs the method for all entries and does nothing for the current markerID, but adds a Score for every entry with another markerID. How can I get it to do what I want? if (cursor.moveToFirst()) { do { Log.d("Database", "Inhalt: "+cursor.getString(0) + cursor.getString(1)); if (Integer.parseInt(cursor.getString(0)) < 5 && cursor.getString(1).equals(markerID)) { Log.d("Database", "Update"); dbh.updateScore(dbh, Integer.parseInt(cursor.getString(0)), markerID, score); finish(); } else if (Integer.parseInt(cursor.getString(0))== 5 &&cursor.getString(1).equals(markerID)) { Log.d("Database", "Nothing"); finish(); } else if (!cursor.getString(1).equals(markerID)){ Log.d("Database", "Add Score"); dbh.addScore(dbh, score, markerID); finish(); } } while (cursor.moveToNext()); } else { Log.d("Database", "Add Score"); dbh.addScore(dbh, score, markerID); finish(); } cursor.close(); Here is the getScore method from the database: public Cursor getScore(DbHelper dbh) { dbase = dbh.getReadableDatabase(); String columns[] = {COLUMN_SCORE, COLUMN_MARKERID}; Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null); return cursor; }

1 个答案:

答案 0 :(得分:0)

您不需要查看所有条目以检查是否有具有特定标记的条目;只要询问数据库:

db = dbh.getWritableDatabase();
try {
    long score = DatabaseUtils.longForQuery(db,
                "SELECT Score FROM MyTable WHERE MarkerID = ?",
                new String[]{ markerID });
    if (score < 0) { // not found?
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_MARKERID, markerID);
        cv.put(COLUMN_SCORE, ...);
        db.insertOrThrow(SCORE_TABLE, null, cv);
    } else if (score < 5) {
        // nothing
    } else {
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_SCORE, ...);
        db.update(SCORE_TABLE, cv,
                  "MarkerID = ?", new String[]{ markerID });
    }
} finally {
    db.close();
}