Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

foreign key constraint ON DELETE CASCADE not working in sqlite database on android

I have "days" table created as follows

"create table days(" +
            "day_id  integer primary key autoincrement, " +
            "conference_id integer , " +
            "day_date text, " +
            "day_start_time text, " +
            "day_end_time text, " +
            "day_summary text, " +
            "day_description text)";

and i have tracks table created as follows

CREATE_TABLE_TRACK = "create table track(" +
        "track_id integer primary key autoincrement," +
        "day_id integer,"+
        "track_name text," +
        "track_description text," +
        " FOREIGN KEY(day_id) REFERENCES days(day_id) ON DELETE CASCADE )";

as shown above i have foreign key day_id referencing to the day_id of table days...

So what i want is if i delete the day then corresponding track should also be deleted... But it does't happen in my case..

I have sqlite with version 3.5.9

And also i have added 1 line in my helper class as

> db.execSQL("PRAGMA foreign_keys=ON;");

but is still won't work.. please help me out..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Cascading delete isn't supported until Sqlite version 3.6.19, which is first included on Android 2.2.

Fortunately there is an alternative.

You can execute another query like this below your create table query:

db.execSQL("CREATE TRIGGER delete_days_with track BEFORE DELETE ON track "
       +  "FOR EACH ROW BEGIN"
       +         " DELETE FROM days WHERE track.day_id = days.day_id "
       +  "END;");

Note that delete_days_with_track is just a name descriptive of what the trigger does, and this is just the pattern I use; I believe you could name it anything you wish.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...