我有三张表:症状,疾病,symDisease
| Disease | | Symptoms | | symDisease |
--------------- -------------- ----------------
| id(pk) | | id(pk) | | diseaseId(fk)|
| name | | symp | | symptomId(fk)|
检查数组中值的存在并插入数据库的代码:
public Cursor checkExistence(){
Cursor c=null;
String[] values={"headache","heartburns"};
SQLiteDatabase db= getReadableDatabase();
db.beginTransaction();
try {
for (String value : values) {
long count = DatabaseUtils.queryNumEntries(db,
TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value });
if (count == 0) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_SYMP, value);
db.insert(TABLE_SYMPTOMS, null, cv);
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return c;
}
上面的代码检查表格症状中是否存在String[] values={"headache","heartburns"};
中的值。在这种情况下,headache
存在,但heartburns
在表症状中不存在,因此会将其插入到表中。
现在想要获取heartburns
的id并将其与diseaseid
一起插入到表symDisease中。示例diseaseid of Malaria = 1
。
所以在表symDisease插入的最后,它应该像(idOfMalaria, idOfHeartburns)
。
答案 0 :(得分:2)
您可以获取插入的行的ID:
long rowInserted = db.insert(TABLE_SYMPTOMS, null, cv);
if (rowInserted != -1) {
//New row was added correctly, and the id of the inserted
//value is in rowInserted.
}else{
//Error on inserted
}