SQlite - Android - 外键语法
我一直在尝试让外键在我的 Android SQLite 数据库中工作。我已经尝试过以下语法,但它给了我一个强制关闭:
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: 错误/AndroidRuntime(312):原因: android.database.sqlite.SQLiteException: 国外未知专栏“taskCat” 关键定义:创建表提醒 (_id 整数主键 自动增量,task_title 文本不是 null,注释文本不为空, 提醒日期时间文本不为空, 外键(taskCat)参考 类别(_id));
I've been trying to get foreign keys working within my Android SQLite database. I have tried the following syntax but it gives me a force close:
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+"));";
Any ideas what I might be doing wrong? if you need to see the other table structure then I can, its just a very simple structure for the second with an ID and a name.
Edit:
Here is the error:
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));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须首先定义
TASK_CAT
列,然后在其上设置外键。您可以在 sqlite 外键 doc 上找到更多信息。
You have to define your
TASK_CAT
column first and then set foreign key on it.More information you can find on sqlite foreign keys doc.
由于我无法发表评论,因此除了 @jethro 答案之外还添加了此注释。
我发现您还需要将 FOREIGN KEY 行作为创建表语句的最后一部分,否则在安装应用程序时会出现语法错误。我的意思是,你不能做这样的事情:
我将 TASK_DATE_TIME 放在外键行之后。
Since I cannot comment, adding this note in addition to @jethro answer.
I found out that you also need to do the FOREIGN KEY line as the last part of create the table statement, otherwise you will get a syntax error when installing your app. What I mean is, you cannot do something like this:
Where I put the TASK_DATE_TIME after the foreign key line.
正如您在错误描述中看到的,您的表包含列(_id、tast_title、notes、reminder_date_time),并且您尝试从“taskCat”列添加外键,但它在您的表中不存在!
As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!