本文介绍如何在Android SQLite中使用外键 (foreign key) 实现 —— 删除主表某一行时自动删除子表关联内容。
前提:android SQLite 数据库已建立 ,主表 CourseInfo,子表OriginalSchedule。
目标:定义子表OriginalSchedule 的列 COLUMN_COURSE_ID为 外键(foreign key),关联CourseInfo 主键_ID。当删除CourseInfo 某一行时同时删除 OriginalSchedule 中的关联行 。
1、主表Course和子表OriginalSchedule的定义
public class TestDbHelper extends SQLiteOpenHelper {
……
@Override public void onCreate(SQLiteDatabase sqLiteDatabase)
{
// Create a table to hold Characters' learning status and display sequence.
Log.v(LOG_TAG, "TestDbHelper onCreate");
final String SQL_CREATE_COURSE_INFO_TABLE = "CREATE TABLE " + CourseInfo.TABLE_NAME + " (" +
CourseInfo._ID + " INTEGER PRIMARY KEY NOT NULL, " +
CourseInfo.COLUMN_NUMBER_OF_CLASSES + " INTEGER NOT NULL);";
final String SQL_CREATE_ORIGINAL_SCHEDULE_TABLE = "CREATE TABLE " + OriginalSchedule.TABLE_NAME + " (" +
OriginalSchedule._ID + " INTEGER PRIMARY KEY NOT NULL, " +
OriginalSchedule.COLUMN_COURSE_ID + " INTEGER NOT NULL,+
OriginalSchedule.COLUMN_SEQUENCE_ID + " INTEGER NOT NULL" +
");";
……
}
2、 定义OriginalSchedule中的外键(foreign key)
final String SQL_CREATE_ORIGINAL_SCHEDULE_TABLE = "CREATE TABLE " + OriginalSchedule.TABLE_NAME + " (" +
OriginalSchedule._ID + " INTEGER PRIMARY KEY NOT NULL, " +
OriginalSchedule.COLUMN_COURSE_ID + " INTEGER NOT NULL REFERENCES " + CourseInfo.TABLE_NAME + "(" +CourseInfo._ID + ") ON DELETE CASCADE,"+
OriginalSchedule.COLUMN_SEQUENCE_ID + " INTEGER NOT NULL" +
");";
或者
final String SQL_CREATE_ORIGINAL_SCHEDULE_TABLE = "CREATE TABLE " + OriginalSchedule.TABLE_NAME + " (" + OriginalSchedule._ID + " INTEGER PRIMARY KEY NOT NULL, " +
OriginalSchedule.COLUMN_COURSE_ID + " INTEGER NOT NULL, " +
OriginalSchedule.COLUMN_SEQUENCE_ID + " INTEGER NOT NULL," +
"FOREIGN KEY("+ OriginalSchedule.COLUMN_COURSE_ID +") REFERENCES " + CourseInfo.TABLE_NAME + "(" +CourseInfo._ID + ") ON DELETE CASCADE);";
3、打开SQLite 外键开关
在TestDbHelper 中重写onOpen,打开外键开关。
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if(!db.isReadOnly()) {
//Enable foreign key constraints
Log.e(LOG_TAG,"open foreign_key");
db.execSQL("PRAGMA foreign_keys = ON;");
}
}
代码修改结束。
4、相关知识
-----------------------------------------------------------------------------
That's all. Thank you.