不对NULL强制使用唯一索引约束

时间:2014-09-23 04:24:17

标签: android sqlite android-sqlite

我在sqlite数据库中创建了一个具有复合唯一索引约束的表。问题是没有强制执行约束。我能够使用相同的唯一键(col2 NOT NULL,col4)插入多行(“testvalue”,NULL)。

根据documentation

For the purposes of UNIQUE constraints, NULL values are considered distinct from all other values, including other NULLs.

那么我如何使用NULL值强制执行唯一约束?

这是描述我的表的类:

public class myTable{
    /*table name*/
    public static final String TABLE_NAME = "myTable";

    /*column names*/
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_1 = "col1";
    public static final String COLUMN_2 = "col2";
    public static final String COLUMN_3 = "col3";
    public static final String COLUMN_4 = "col4";

    /*create table script*/
    public static final String CREATE_TABLE = 
        "CREATE TABLE " + TABLE_NAME
        + "( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT"
        + ", " + COLUMN_1 + " INTEGER"
        + ", " + COLUMN_2 + " INTEGER NOT NULL"
        + ", " + COLUMN_3 + " TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP"
        + ", " + COLUMN_4 + " TEXT"
        + ", FOREIGN KEY(" + COLUMN_2 + ") REFERENCES " + Table_other.TABLE_NAME + "(" + Table_other.COLUMN_ID + ")"
        + ", FOREIGN KEY(" + COLUMN_1 + ") REFERENCES " + Table_yetanother.TABLE_NAME + "(" + Table_yetanother.COLUMN_ID + ")"
        + ")";

    /*create index script */
    public static final String CREATE_INDEX =   
        "CREATE UNIQUE INDEX UIDX ON " + TABLE_NAME 
        + "(" + COLUMN_2 + "," + COLUMN_4 + ");";


}

1 个答案:

答案 0 :(得分:-1)

SQLite默认关闭外键约束。

您必须通过执行以下操作明确启用它:

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