How can we remove a foreign key in sqlite?

I am working with a SQLite database. I have a table that contains primary keys from 2 other tables as foreign keys; I want to delete one of them. Here is the table code:

protected static final String Item_places=(" CREATE TABLE " + Item_place + "(" + place_id + " INTEGER ," + Item_id + " INTEGER ," + "FOREIGN KEY("+place_id+ ") REFERENCES " + PlaceTable + "("+ PlaceID+ " ) ON DELETE CASCADE" + "FOREIGN KEY("+Item_id+ ") REFERENCES "+ contentTable+ "("+contentID+"));"); 
+4
source share
2 answers

This is an old question, but it is best to give an updated answer.

Since API 16 (Aka Android 4.1), you can enable FK restrictions using SQLiteDatabase#setForeignKeyConstraintsEnabled(boolean enabled) .

As for documents :

Sets whether foreign key restrictions are allowed for the database.

By default, foreign key restrictions are not applied to the database. This method allows the application to include foreign key constraints. It must be called every time the database is opened so that external key constraints are enabled for the session.

To make this work, in your custom SQLiteOpenHelper use the following code:

 @Override public void onConfigure(SQLiteDatabase db) { // Enable FK constraints. db.setForeignKeyConstraintsEnabled(true); super.onConfigure(db); } 
+6
source

You will need the ALTER TABLE DROP CONSTRAINT , but SQLite does not support this , see How to make a DROP constraint from the sqlite table (3.6.21)? for a workaround.

+5
source

Source: https://habr.com/ru/post/1369410/


All Articles