2014-09-23 63 views
1

我已經在我的sqlite數據庫中創建了一個具有複合唯一索引約束的表。問題在於約束沒有被執行。我能夠用(「testvalue」,NULL)的相同唯一鍵(col2 NOT NULL,col4)插入多行。唯一索引約束沒有被強制爲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 + ");"; 


} 
+0

參見[NULL處理SQLite中與其他數據庫引擎(http://www.sqlite.org/nulls.html)細節。 – 2014-09-23 07:08:54

+0

@CL。謝謝。這是一篇不錯的文章。我已經經歷了,但我仍然在尋找解決方案。我想唯一的方法就是在這裏 - http://stackoverflow.com/a/12095133/2105986 – faizal 2014-09-23 07:14:40

回答

-1

的SQLite有外鍵約束,默認關閉。

你必須明確地打開它通過執行以下操作:爲更多

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

這不回答這個問題。 – 2014-09-23 07:07:04

+0

這不能解決我的問題,但您已經注意到了我的問題!對於Android中的SQlite版本,這是否也適用?每當我做一個插入或一次創建/更新數據庫時,是否運行此PRAGMA命令? – faizal 2014-09-23 07:20:29

+1

@faizal您需要在[onCreate()](http:// localhost)中調用[setForeignKeyConstraintsEnabled()](http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#setForeignKeyConstraintsEnabled%28boolean%29) //developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onConfigure%28android.database.sqlite.SQLiteDatabase%29)。 – 2014-09-23 07:22:29