BoneStarr
BoneStarr

Reputation: 195

Foreign keys definition

Hi I'm trying to create an sqldatabase and I'm trying to define my foreign keys in the oncreate method. I just wanted to know if this would be the correct definition for something like this:

Route table: id, name

Stop table: id, name

Time table: id, foreign key to bus, foreign key to stop

    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + DATABASE_STOPTABLE + " (" +
        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_STOPS + " TEXT NOT NULL);" +
        "CREATE TABLE " + DATABASE_BUSTABLE + " (" + 
        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_BUSES + " TEXT NOT NULL);" +
        "CREATE TABLE " + DATABASE_TIMETABLE + " (" + 
        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_BUSES + " TEXT NOT NULL, " +
                    + KEY_TIME + " integer,"
                    + " FOREIGN KEY ("+KEY_TIME+") REFERENCES "+DATABASE_STOPTABLE+"         ("+KEY_STOPS+"), " +
                      + " FOREIGN KEY ("+KEY_TIME+") REFERENCES "+DATABASE_BUSTABLE+"         ("+KEY_BUSES+"));"
                );
    }

Upvotes: 0

Views: 269

Answers (1)

Marcos
Marcos

Reputation: 4643

It's ok. Remember that you need to enable:

@Override
public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
    if (!db.isReadOnly()) {
        db.execSQL("PRAGMA foreign_keys=ON;");
    }
}

The '+' character is twice before KEY_TIME + " integer,"

Upvotes: 2

Related Questions