插入表A中不存在并插入表B的特定数组值的id

时间:2017-02-14 16:23:50

标签: android sqlite

我有三张表:症状,疾病,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)

1 个答案:

答案 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
}