2011-03-13 65 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放在外键行后面。