我有表 medical_user 和表 operation_issue :
CREATE TABLE medical_user(_id INTEGER,medical_id TEXT,creation_date DATE,update_date DATE,birth_date DATE,gender TEXT,bmi DOUBLE,is_deleted INTEGER DEFAULT 0 NOT NULL CHECK(is_deleted IN (0,1)) ,PRIMARY KEY (medical_id,creation_date));
CREATE TABLE operation_issue(operation_issue_name TEXT,medical_user_id TEXT,creation_date DATE,update_date DATE,PRIMARY KEY (operation_issue_name) FOREIGN KEY(medical_user_id) REFERENCES medical_user(medical_id) ON UPDATE CASCADE);
首先,我使用以下方法成功插入用户: User70666661 :
public long insert(MedicalUser medicalUser) {
if (medicalUser == null)
return -1;
try {
ContentValues values = getUserContentValues(medicalUser);
long ret = database.insertOrThrow(DBContracts.MedicalUserTable.TABLE_NAME, null, values);
UtilsRG.log.info("Inserted user(" + medicalUser.getMedicalId() + ") into databse successfully");
return ret;
} catch (Exception e) {
UtilsRG.error("Failed to insert medicalUser: " + medicalUser.getMedicalId() + " ErrorMessage:" + e.getLocalizedMessage());
return -1L;
}
}
获取此日志:已成功将用户(User70666661)插入数据库
然后我尝试插入 operation_issue
android.database.sqlite.SQLiteException:外键不匹配 - “operation_issue”引用“medical_user”(代码1):,而 编译:INSERT INTO operation_issue VALUES('超级热门 issue','User70666661','2016-11-10 12:10:07.080','2016-11-10 12:10:07.081' );
更新1:
使用此getUserContentValues()方法:
private ContentValues getUserContentValues(MedicalUser medicalUser) {
ContentValues values = new ContentValues();
if (medicalUser.getMedicalId() != null)
values.put(DBContracts.MedicalUserTable.COLUMN_NAME_MEDICAL_ID, medicalUser.getMedicalId());
if (medicalUser.getCreationDate() != null) {
values.put(DBContracts.MedicalUserTable.COLUMN_NAME_CREATION_DATE, UtilsRG.dateFormat.format(medicalUser.getCreationDate()));
values.put(DBContracts.MedicalUserTable.COLUMN_NAME_UPDATE_DATE, UtilsRG.dateFormat.format(medicalUser.getUpdateDate()));
}
if (medicalUser.getBirthDate() != null)
values.put(DBContracts.MedicalUserTable.COLUMN_NAME_BIRTH_DATE, UtilsRG.dateFormat.format(medicalUser.getBirthDate()));
if (medicalUser.getGender() != null && (!medicalUser.getGender().equals("")))
values.put(DBContracts.MedicalUserTable.COLUMN_NAME_GENDER, medicalUser.getGender().name());
if (medicalUser.getBmi() > 0)
values.put(DBContracts.MedicalUserTable.COLUMN_NAME_BMI, medicalUser.getBmi());
values.put(DBContracts.MedicalUserTable.COLUMN_MARKED_AS_DELETE, (medicalUser.isMarkedAsDeleted()) ? 1 : 0);
return values;
}