我的表遇到问题,第一个表创建了对第二个表中数据的引用,CARD_ID增量很好,但CARD_INFO_TABLE中的外键不会自动增量甚至意识到它是自动增量的外键,所以我想知道,我哪里错了!?
public static final String CREATE_CARD_TABLE = "CREATE TABLE "
+ CARD_TABLE + "(" + CARD_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + CARD_NAME
+ " TEXT )";
public static final String CREATE_CARDINFO_TABLE = "CREATE TABLE "
+ CARD_INFO_TABLE + "(" + CARD_ID2
+ " INTEGER, " + CARD_NAME2
+ " TEXT, " + CARD_WEIGHT
+ " REAL, " + CARD_REPS
+ " INTEGER, "
+ " FOREIGN KEY " + "("+ CARD_ID2 +")"+ " REFERENCES " + CARD_TABLE + "("+CARD_ID+"));";
然后我按如下方式向他们插入数据,我哪里错了?
public void insertEntry(String name, double weight, int reps) {
if(flag == 0) {
open();
database.beginTransaction();
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(DataBaseHelper.CARD_NAME, name);
// Insert the row into your table
database.insert(DataBaseHelper.CARD_TABLE, null, newValues);
flag = 1;
database.setTransactionSuccessful();
database.endTransaction();
close();
}
open();
database.beginTransaction();
ContentValues newValues2 = new ContentValues();
// Assign values for each row.
newValues2.put(DataBaseHelper.CARD_NAME2, name);
newValues2.put(DataBaseHelper.CARD_WEIGHT, weight);
newValues2.put(DataBaseHelper.CARD_REPS, reps);
// Insert the row into your table
database.insert(DataBaseHelper.CARD_INFO_TABLE, null, newValues2);
database.setTransactionSuccessful();
database.endTransaction();
close();
}
答案 0 :(得分:0)
foreign key constraint只是一个约束,即它只会检查您对数据所做的更改是否会造成错误的关系。
要创建这些关系,您仍然需要插入相同的数据(并且您不应该将操作分成两个事务,并且必须正确处理异常):
database.beginTransaction();
try {
long cardID = DatabaseUtils.longForQuery(database,
"SELECT "+CARD_ID+" FROM "+CARD_TABLE+
" WHERE "+CARD_NAME+" = ?",
new String[] { name });
if (cardID < 0) { // not found?
ContentValues card = new ContentValues();
card.put(DataBaseHelper.CARD_NAME, name);
cardID = database.insert(DataBaseHelper.CARD_TABLE, null, card);
}
ContentValues info = new ContentValues();
info.put(DataBaseHelper.CARD_ID2, cardID);
info.put(DataBaseHelper.CARD_NAME2, name);
info.put(DataBaseHelper.CARD_WEIGHT, weight);
info.put(DataBaseHelper.CARD_REPS, reps);
database.insert(DataBaseHelper.CARD_INFO_TABLE, null, info);
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}