public void onCreate(sqliteDatabase db) { // TODO Auto-generated method stub String classessql = "CREATE TABLE classes(class_id varchar(10) primary key," + "class_name varchar(20))"; String studentssql = "CREATE TABLE students(student_id varchar(10) primary key," + "student_name varchar(20),score varchar(4),class_id varchar(10)," + "foreign key (class_id) references classes(class_id) " + "on delete cascade on update cascade )"; db.execsql(classessql); Log.d("my","create table classes:"+classessql); db.execsql(studentssql); Log.d("my","create table students:"+studentssql); }
在创建表的时候有创建外键,进行了级联更新和级联删除,但是在删除一个班级的时候,发先属于该班级的学生却没有删除,也就是说
on delete cascade on update cascade
失效了。
经查资料知道:sqlite在3.6.19版本中才开始支持外键约束,但是为了兼容以前的程序,默认并没有启用该功能,如果要启用该功能每次都要需要使用如下语句:PRAGMA foreign_keys = ON来打开。
也就是说,在执行删除一个班级的语句的时候需要执行db.execsql("PRAGMA foreign_keys=ON")
/** * 删除一个班级 * 同时会删除students中该班级的学生 * @param class_id */ public void deleteClass(String class_id) { sqliteDatabase localsqliteDatabase = this.dbhelper.getWritableDatabase(); //设置了级联删除和级联更新 //在执行有级联关系的语句的时候必须先设置“PRAGMA foreign_keys=ON” //否则级联关系默认失效 localsqliteDatabase.execsql("PRAGMA foreign_keys=ON"); Object[] arrayOfObject = new Object[1]; arrayOfObject[0] =class_id; localsqliteDatabase.execsql("delete from classes where class_id=?",arrayOfObject); localsqliteDatabase.close(); }原文链接:https://www.f2er.com/sqlite/200541.html