为什么我不能使用带有外键的桌子'?

时间:2016-02-06 15:11:13

标签: android sqlite foreign-keys android-sqlite

当我创建2个表时,没有外键一切正常,但是当我添加外键时,我的应用程序不会创建表。

请帮帮我。

//table1
private static final String CREATE_TABLE1 = "create table "
        + TABLE_MEMBER + "(" + MIEMBRO_ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + MIEMBRO_NOMBRE + " TEXT);";
//table2
private static final String CREATE_TABLE2= "create table "
        +EJERCICIOS_TABLA+"("+EJERCICIO_ID
        +" INTEGER PRIMARY KEY AUTOINCREMENT, "
        +EJERCICIO_NOMBRE+" TEXT);";
//table3
private static final String CREATE_TABLE3= "create table "
        +REGISTRO_TABLA+"("
        +ID_REG+"INTEGER PRIMARY KEY AUTOINCREMENT, "
        +ID_U+" INTEGER, "
        +ID_E+" INTEGER, "
        +RM_MAX+" REAL, "

        +" FOREIGN KEY (" +ID_U+ ") REFERENCES "+TABLE_MEMBER+" ("+ MIEMBRO_ID +") ON DELETE CASCADE,"
        +" FOREIGN KEY ("+ ID_E +") REFERENCES "+EJERCICIOS_TABLA+" ("+ EJERCICIO_ID +")ON DELETE CASCADE;";

这里是onCreate()方法:

public void onCreate(SQLiteDatabase db) {
    if (!db.isReadOnly()) {
        // Enable foreign key constraints
        db.execSQL("PRAGMA foreign_keys=ON;");
    }

    db.execSQL(CREATE_TABLE1);
    db.execSQL(CREATE_TABLE2);
    db.execSQL(CREATE_TABLE3);
    db.execSQL("INSERT INTO "+EJERCICIOS_TABLA+" ("+EJERCICIO_NOMBRE+") VALUES('Sentadilla') ");

    db.execSQL("insert into "+TABLE_MEMBER+" ("+MIEMBRO_NOMBRE+") values('Pedro')");

当我创建Table1和Table2时,一切正常,但是当我创建table3失败时。

2 个答案:

答案 0 :(得分:0)

你在最后一个CASCADE之后错过了一个结束。

它应该是这样的:

//table3
private static final String CREATE_TABLE3= "create table "
    +REGISTRO_TABLA+"("
    +ID_REG+"INTEGER PRIMARY KEY AUTOINCREMENT, "
    +ID_U+" INTEGER, "
    +ID_E+" INTEGER, "
    +RM_MAX+" REAL, "

    +" FOREIGN KEY (" +ID_U+ ") REFERENCES "+TABLE_MEMBER+" ("+ MIEMBRO_ID +") ON DELETE CASCADE,"
    +" FOREIGN KEY ("+ ID_E +") REFERENCES "+EJERCICIOS_TABLA+" ("+ EJERCICIO_ID +")ON DELETE CASCADE);"; 

答案 1 :(得分:0)

我不确定这是否正确:

public void onCreate(SQLiteDatabase db) {
    if (!db.isReadOnly()) {
        // Enable foreign key constraints
        db.execSQL("PRAGMA foreign_keys=ON;");
    }

我读到外键总是关闭,我把它添加到onCreate方法。