Android 复合键,您的主键不是唯一的
我有一个表,它使用复合键作为主键。这是我的创建表代码Android 复合键,您的主键不是唯一的,android,composite-key,sqlite,Android,Composite Key,Sqlite,我有一个表,它使用复合键作为主键。这是我的创建表代码 private static final String db_createorderdtl = "create table if not exists " + ORDER_DTL + "(" + ORDER_ID +" varchar not null, " + COLUMN_ID+ " integer not null, " + QUANTITY + " varchar(3) not nul
private static final String db_createorderdtl = "create table if not exists "
+ ORDER_DTL + "("
+ ORDER_ID +" varchar not null, "
+ COLUMN_ID+ " integer not null, "
+ QUANTITY + " varchar(3) not null," +
" foreign key ("+ORDER_ID+") references "+TABLE_ORDER+"("+ORDER_ID+"),"+
" foreign key ("+COLUMN_ID+") references "+TABLE_NAME+"("+COLUMN_ID+"), "+
"primary key ("+ORDER_ID+"," +COLUMN_ID+ "));";
当我在此表中插入多个项目、相同的订单号、不同的列号时,第一个项目没有问题,但当插入第二个项目时,我出现了一个错误,表明我的主键不是唯一的,请参考订单号。就像程序不理解我使用的是复合键一样。我应该在我的程序代码中声明一些东西吗?这是我插入的代码:
public orderdtl createorderdtl(String orderid, String Id, String qty) {
ContentValues values = new ContentValues();
values.put(DBHelper.ORDER_ID, orderid);
values.put(DBHelper.COLUMN_ID, Id);
values.put(DBHelper.QUANTITY, qty);
database.insert(DBHelper.ORDER_DTL, null,values);
Cursor cursor = database.query(DBHelper.ORDER_DTL,
allorderdtl, DBHelper.ORDER_ID + "=" + orderid, null,
null, null, null);
orderdtl neworderdtl = null;
if (cursor.moveToFirst()) {
neworderdtl = cursorToorderdtl(cursor);
}
cursor.close();
return neworderdtl;
}
看起来您没有在用于插入操作的ContentValues对象中设置列ID。但是,列_ID是主键的一部分,在每次插入时可能默认为0。这可能是主键不唯一错误的原因。@NobuGames查看我的编辑在这两种情况下orderid和Id的实际值是什么?orderid=yyyyMMddhhmmss示例20140125123030和Id=1,2,3autoincrement@CL.orderid=yyyyMMddhhmmss示例20140125123030和id=1,2,3自动增量