【问题标题】:Should I enable foreign key constraint in onOpen or onConfigure我应该在 onOpen 还是 onConfigure 中启用外键约束
【发布时间】: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");
    }
}

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    onConfigure() 是理想的,但它只在 API 16 及更高版本上调用。如果你的minSdkVersion 是 16 岁或以上,请使用它。

    onOpen() 的问题是它只在可能的onCreate()/onUpgrade() 等之后才被调用。如果您在onCreate()/onUpgrade() 中有需要强制执行外键的SQL,那么设置为时已晚onOpen() 中的外键编译指示。对于minSdkVersion < 16,请考虑以下事项:

    • 始终在onOpen() 中启用外键。

    • 如果您的 onCreate()/onUpgrade() 需要强制执行外键,也可以在那里启用它们。真正启用它们可能两次并没有什么坏处。

    【讨论】:

      猜你喜欢
      • 2011-05-14
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2015-09-22
      • 2011-06-25
      • 1970-01-01
      相关资源
      最近更新 更多