Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how we can delete foreign-key in sqlite?

Tags:

android

sqlite

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("+place_id+ ") REFERENCES " + PlaceTable + "("+ PlaceID+ " ) ON DELETE CASCADE" 
    + "FOREIGN KEY("+Item_id+ ") REFERENCES "+ contentTable+ "("+contentID+"));"); 
like image 499
kshf_x Avatar asked Dec 27 '22 15:12

kshf_x


2 Answers

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.

like image 91
Philipp Reichart Avatar answered Jan 11 '23 03:01

Philipp Reichart


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);
}
like image 27
Mauker Avatar answered Jan 11 '23 03:01

Mauker