SQLite table constraint unique and ON CONFLICT REPLACE usage

谁说胖子不能爱 提交于 2019-12-24 07:25:07

问题


Please read before make it Duplicate.

I am trying to insert longitude and latitude values in SQLite table and i want it to be unique value, after some research for that i have found this and this answers very helpful, although they both are written for simple queries and i am not able to find how to fit my query with both constraints unique and ON_CONFLICTION_REPLACE

query is as follow,

 private static final String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_LOCATIONS + "("
                + UID + " TEXT PRIMARY KEY," + ADDRESS + " TEXT,"
                + LONGITUDE + " TEXT unique," + LATITUDE + " TEXT unique" + ")";

but this unique doesn't made any differences, is it compulsion to use ON_CONFLICTION_REPLACE in my case?

From Ayman's answer i got that i can apply unique on multiple columns together but i still getting duplicate values after insertion. can anyone make appropriate query from my query and help me understand all things? Thanks


回答1:


Change your table structure to this

private static final String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_LOCATIONS + "("
            + UID + " TEXT PRIMARY KEY," + ADDRESS + " TEXT,"
            + LONGITUDE + " TEXT," + LATITUDE + " TEXT,
            UNIQUE(" + LOGITUDE + "," + LATITUDE + ") ON CONFLICT REPLACE)";

Then when you do the insert use the below method

ContentValues insertValues = new ContentValues();
insertValues.put(LATITUDE, latitude);
insertValues.put(LOGITUDE, longitude);
db.insertWithOnConflict(TABLE_LOCATIONS, null, insertValues, SQLiteDatabase.CONFLICT_REPLACE);


来源:https://stackoverflow.com/questions/39571253/sqlite-table-constraint-unique-and-on-conflict-replace-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!