2011-03-13 34 views
48

我一直在嘗試讓外鍵在我的Android SQLite數據庫中工作。我試過下面的語法,但它給了我一個力量關閉:SQlite - Android - 外鍵語法

private static final String TASK_TABLE_CREATE = "create table " 
      + TASK_TABLE + " (" + TASK_ID 
      + " integer primary key autoincrement, " + TASK_TITLE 
      + " text not null, " + TASK_NOTES + " text not null, " 
    + TASK_DATE_TIME + " text not null, FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"));"; 

任何想法,我可能會做錯嗎?如果你需要查看其他表結構,那麼我可以,它只是一個非常簡單的結構,第二個具有ID和名稱。

編輯:

以下是錯誤:

03-13 13:42:35.389: ERROR/AndroidRuntime(312): Caused by: android.database.sqlite.SQLiteException: unknown column "taskCat" in foreign key definition: create table reminders (_id integer primary key autoincrement, task_title text not null, notes text not null, reminder_date_time text not null, FOREIGN KEY (taskCat) REFERENCES category (_id));

回答

99

你必須定義你的TASK_CAT列,然後設置外鍵就可以了。

private static final String TASK_TABLE_CREATE = "create table " 
     + TASK_TABLE + " (" 
     + TASK_ID + " integer primary key autoincrement, " 
     + TASK_TITLE + " text not null, " 
     + TASK_NOTES + " text not null, " 
     + TASK_DATE_TIME + " text not null," 
     + TASK_CAT + " integer," 
     + " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));"; 

更多關於sqlite外鍵的信息doc

+5

該解決方案對我無效。我找到的解決方案是將其全部定義在一行中,但語法略有不同。我做了這個,而不是最後兩行: TASK_CAT +「INTEGER REFERENCES」+ CAT_TABLE +「);」; – HotN 2011-09-01 15:59:50

+0

@你好,你是好朋友。你的解決方案也適用於我。謝謝 – blueware 2015-04-22 14:51:47

+0

@jetho我想添加功能,一旦父鍵刪除所有孩子的列記錄也應該刪除。 – UnKnown 2017-02-13 06:33:55

1

正如您在錯誤描述中看到的那樣,表中包含列(_id,tast_title,notes,reminder_date_time),並且您嘗試從列「taskCat」添加外鍵,但它不存在於您的表中!

9

由於我不能發表評論,除了@jethro答案外,添加這個註釋。

我發現你還需要做FOREIGN KEY行作爲創建表語句的最後一部分,否則在安裝應用程序時會出現語法錯誤。我的意思是,你不能這樣做:

private static final String TASK_TABLE_CREATE = "create table " 
    + TASK_TABLE + " (" + TASK_ID 
    + " integer primary key autoincrement, " + TASK_TITLE 
    + " text not null, " + TASK_NOTES + " text not null, " 
+ TASK_CAT + " integer," 
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+" ("+CAT_ID+"), " 
+ TASK_DATE_TIME + " text not null);"; 

在哪裏我把TASK_DATE_TIME放在外鍵行後面。