简体   繁体   中英

Android SQLite INSERT OR IGNORE doesn't work

Why do the IGNORE statement doesn't work? Everytime I run this the same value were insert in the database and I don't know why?

        myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
        myDB.execSQL("INSERT OR IGNORE INTO " + MY_DB_TABLE + "(db_datum, db_zahlen, db_scheine)" 
                +"VALUES ('"+datum+"',"+
                "'"+zahlen+"',"+
                "'"+9+"');");

db schema is:

  • db_datum (varchar(100))

  • db_zahlen (varchar(100))

  • db_scheine (integer)

I have the 2 String "datum" and "zahlen" and would like to insert them in the database. Now the problem is, if the same strings are already in the db and the code run again they sould be ignored and never insert again.

You can use insertWithOnConflict. Ex:

mDb.insertWithOnConflict(DATABASE_TABLE, null, initialValues, SQLiteDatabase.CONFLICT_IGNORE);

You should not use execSQL to do an INSERT command (check the docs).

Use myDB.insertOrThrow(...) instead :

ContentValues cv = new ContentValues();
cv.put("db_datum", datum);
cv.put("db_zahlen", zahlen);
cv.put("db_scheine", 9);
myDB.insertOrThrow(MY_DB_TABLE, null, cv);

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