I am working with an SQLite database. I have a table which contain the primary keys of 2 other tables as foreign keys; I want to delete one of them. Here is the code for the table:
protected static final String Item_places=(" CREATE TABLE "
+ Item_place + "("
+ place_id + " INTEGER ,"
+ Item_id + " INTEGER ,"
+ "FOREIGN KEY("开发者_StackOverflow中文版+place_id+ ") REFERENCES " + PlaceTable + "("+ PlaceID+ " ) ON DELETE CASCADE"
+ "FOREIGN KEY("+Item_id+ ") REFERENCES "+ contentTable+ "("+contentID+"));");
You would need an ALTER TABLE DROP CONSTRAINT
command but SQLite doesn't support this, see How do I DROP a constraint from a sqlite (3.6.21) table? for a workaround.
This is an old question, but it's best to provide an updated answer.
Since API 16 (Aka Android 4.1), it's possible to turn on the FK constraints using SQLiteDatabase#setForeignKeyConstraintsEnabled(boolean enabled)
.
As per the docs:
Sets whether foreign key constraints are enabled for the database.
By default, foreign key constraints are not enforced by the database. This method allows an application to enable foreign key constraints. It must be called each time the database is opened to ensure that foreign key constraints are enabled for the session.
To make this work, inside your custom SQLiteOpenHelper
use the following code:
@Override
public void onConfigure(SQLiteDatabase db) {
// Enable FK constraints.
db.setForeignKeyConstraintsEnabled(true);
super.onConfigure(db);
}
精彩评论