且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用SQLite在Android的外键约束? Delete(删除)级联

更新时间:2023-02-03 08:29:31

与删除级联外键约束的支持,但你需要启用它们。
我只是增加了以下我的 SQLOpenHelper 的,这似乎这样的伎俩。

  @覆盖
公共无效的OnOpen(SQLiteDatabase DB){
    super.onOpen(DB);
    如果(!db.isReadOnly()){
        //启用外键约束
        db.execSQL(杂foreign_keys = ON;);
    }
}
 

我宣布我引用列如下:

  mailbox_id INTEGER参考邮箱ON DELETE CASCADE
 

I have two tables: tracks and waypoints, a track can have many waypoints, but a waypoint is assigned to only 1 track.

In the way points table I have a column called "trackidfk" which inserts the track_ID once a track is made, however I have not setup Foreign Key constraints on this column.

When I delete a track I want to delete the assigned waypoints, is this possible?. I read about using Triggers but I don't think they are supported in Android.

To create the waypoints table:

public void onCreate(SQLiteDatabase db) {
    db.execSQL( "CREATE TABLE " + TABLE_NAME 
                + " (" 
                + _ID         + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
                + LONGITUDE   + " INTEGER," 
                + LATITUDE    + " INTEGER," 
                + TIME        + " INTEGER,"
                + TRACK_ID_FK + " INTEGER"
                + " );"
              );

    ...
}

Foreign key constraints with on delete cascade are supported, but you need to enable them.
I just added the following to my SQLOpenHelper, which seems to do the trick.

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
    if (!db.isReadOnly()) {
        // Enable foreign key constraints
        db.execSQL("PRAGMA foreign_keys=ON;");
    }
}

I declared my referencing column as follows.

mailbox_id INTEGER REFERENCES mailboxes ON DELETE CASCADE