【发布时间】:2014-05-12 13:00:15
【问题描述】:
我遇到了不同的代码 sn-p,关于在 SQLiteHelper 中启用外键约束。我想知道,如果我也想支持 API onOpen 或 onConfigure 中启用外键约束吗?
这个讨论建议onOpen是正确的地方,在API 16之前:Foreign key constraints in Android using SQLite? on Delete cascade
但是,由于 API 16,官方文档确实提到 onConfigure 是正确的地方。
public void setForeignKeyConstraintsEnabled (boolean enable)
...
A good time to call this method is right after calling openOrCreateDatabase(File, SQLiteDatabase.CursorFactory) or in the onConfigure(SQLiteDatabase) callback.
我可以知道 API 16 和
@Override
public void onOpen(SQLiteDatabase database) {
super.onOpen(database);
if (!database.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
或
// https://stackoverflow.com/questions/13641250/sqlite-delete-cascade-not-working
@SuppressLint("NewApi")
@Override
public void onConfigure(SQLiteDatabase database) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
database.setForeignKeyConstraintsEnabled(true);
} else {
database.execSQL("PRAGMA foreign_keys=ON");
}
}
【问题讨论】: