我正在使用 Android SQLite 数据库,其中有两个表。
TableCHECKPOINTS
定义了 Table 中属性的外键TOUR
。
将数据存储到数据库后,表格Tour
将正确显示。但是,表中具有外键TOUR_ID
的列CHECKPOINTS
保持空白。我不知道为什么。
语法应该没问题,我还设置了PRAGMA foreign_keys = ON;
. 在试验了一段时间后,我Trigger
在onCreate()
我的DatabaseHelper
.
但是,现在我得到一个错误:
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
.
数据库助手:
private static final String TABLE_CREATE_TOUR = "create table TOUR("
+ " ID integer primary key autoincrement, "
+ " NAME varchar(20)) ";
private static final String TABLE_CREATE_CHECKPOINT = "create table CHECKPOINT("
+ " ID integer primary key autoincrement, "
+ " TOUR_ID integer not null, "
+ " FOREIGN KEY (TOUR_ID) REFERENCES TOUR(ID)) ";
public void onCreate(SQLiteDatabase database) {
database.execSQL(TABLE_CREATE_TOUR);
database.execSQL(TABLE_CREATE_CHECKPOINT);
database.execSQL("CREATE TRIGGER fk_checkpoint_tourid BEFORE INSERT ON CHECKPOINT "
+ " FOR EACH ROW BEGIN "
+ " SELECT CASE WHEN ((SELECT ID FROM TOUR WHERE ID = new.TOUR_ID ) IS NULL) "
+ " THEN RAISE (ABORT, 'Foreign Key Violation') END; "
+ " END;");
}
数据源:
public void open() throws SQLException {
database = dbhelper.getWritableDatabase();
// Enable foreign key constraints
if (!database.isReadOnly()) {
database.execSQL("PRAGMA foreign_keys = ON;");
}
}
有没有人知道如何让这件事发生?
编辑:
插入表中TOUR
:
public long InsertTour(String name){
ContentValues values = new ContentValues();
values.put("NAME", name);
return database.insert("TOUR", null, values);
}
该表CHECKPOINT
包含更多如上所述的数据。这是插入:
public Entry createEntry(String PARAM1, String PARAM2, long PARAM3, String PARAM4) {
ContentValues values = new ContentValues();
values.put("COLUMN1", PARAM1);
values.put("COLUMN2", PARAM2);
values.put("COLUMN3", PARAM3);
values.put("COLUMN4", PARAM4);
long insertId = database.insert("CHECKPOINT", null, values);
Cursor cursor = database.query("CHECKPOINT", allColumns, "ID = " + insertId, null, null, null, null);
cursor.moveToFirst();
return cursorToEntry(cursor);
}