Android SQLite3 problem enforcing primary key
I have a listview with a custom adapter that uses an sql cursor. When I add items to my listview, the item will be added to my sqlite3 database and the listview will refresh.
My one problem is that I am able to add duplicate items, and I do not want my application to allow duplicates to be added.
I have added a primary key to my database (on itemNumber), however the database does not seem to be enforcing this. Here is how I create my database:
private static final String DB_CREATE_MASTER = "CREATE TABLE "
+ "MyTable"
+ " (_id INTEGER, itemNumber TEXT,"
+ "itemPlace TEXT," + "itemTimeTEXT,"
+ "itemCode INTEGER,"
+ "dbdatestamp TEXT" + "PRIMARY KEY(itemNumber)" +");";
Does anyone know why I am able to add more than 1 duplicate itemNumber to my listview?
Thanks开发者_开发问答!
EDIT:
private static final String DB_CREATE_MASTER = "CREATE TABLE "
+ "MyTable"
+ " (_id INTEGER PRIMARY KEY, itemNumber TEXT,"
+ "itemPlace TEXT," + "itemTimeTEXT,"
+ "itemCode INTEGER,"
+ "dbdatestamp TEXT" + "UNIQUE(itemNumber)" +");";
EDIT:
This is how I add the itemNumber to the database:
values.put("itemNumber", myClass.itemNumber);
values.put("itemName", myClass.itemName);
values.put("itemTime", myClass.itemTime);
values.put("dbdatestamp", "03/01/1960 08:55");
this.db.insert(MY_TABLE, null, values);
Your primary key consists of 2 fields: _id and itemNumber. That means that a duplicate itemNumber is not enough to enforce the constraint. A duplicate would be an item with the same _id AND itemNumber. You could change the CREATE statement like this
PRIMARY KEY(_id), UNIQUE(itemNumber)
The UNIQUE constraint wouldn't allow duplicate item numbers.
精彩评论