Android中的SQLite:外键和<表约束>预计

问题描述:

我已经搜索了解这个问题的性质,但迄今还没有任何运气。Android中的SQLite:外键和<表约束>预计

我正在做一个RPG风格的待办事项列表来教自己的Android/Java和我正在做两个表:类别(力量,智力等)和任务:名称,描述,EXP等

我希望每个任务都有一个类别,但我得到一个表约束错误。我的代码如下,并且GitHub链接是here

public void onCreate(SQLiteDatabase db){ 
    setForeignKeyConstraintsEnabled(db); 

db.execSQL("CREATE TABLE " + CATEGORY_TABLE_NAME + "(id INTEGER primary key autoincrement NOT NULL, name TEXT, exp INTEGER, level INTEGER)"); 
db.execSQL("CREATE TABLE " + QUEST_TABLE_NAME + "(id INTEGER primary key autoincrement NOT NULL, name TEXT, description TEXT, expValue INTEGER, category INTEGER NOT NULL, FOREIGN KEY (category) REFERENCES categories (id), date TEXT"); 

db.execSQL("INSERT INTO " + CATEGORY_TABLE_NAME + "('name', 'exp', 'level') VALUES ('Strength', 0, 0);"); 
db.execSQL("INSERT INTO " + CATEGORY_TABLE_NAME + "('name', 'exp', 'level') VALUES ('Stamina', 0, 0);"); 
db.execSQL("INSERT INTO " + CATEGORY_TABLE_NAME + "('name', 'exp', 'level') VALUES ('Intelligence', 0, 0);"); 
db.execSQL("INSERT INTO " + CATEGORY_TABLE_NAME + "('name', 'exp', 'level') VALUES ('Social', 0, 0);"); 
db.execSQL("INSERT INTO " + QUEST_TABLE_NAME + "('name', 'description', 'expValue', 'category', 'date') VALUES ('Gym', 'Weightlifting down The Gym', '300', '1', '25/05/2017');"); 
} 

误差以 '日期的文字' 的到来,和错误说:

<table constraint> expected, got 'date'. 

这里有什么问题吗?

+1

试着把它(日期文本)之前外键我不知道,但我认为你需要把所有列前外键 – crammeur

+0

@crammeur如果我移动日期前FOREIGN KEY位,我得到以下错误: ')',DEFERRABLE,MATCH,NOT,ON或逗号预期,文件的意外结束 –

+1

因此更改日期到date1因为日期是函数 – crammeur

你的问题是,你混淆了column_constraint语法与table_constraint语法(即编码其中前者应使用后者)。

您可以通过使用

db.execSQL("CREATE TABLE " + QUEST_TABLE_NAME + "(id INTEGER primary key autoincrement NOT NULL, name TEXT, description TEXT, expValue INTEGER, category INTEGER NOT NULL REFERENCES categories (id), date TEXT");

如下由于是替代语法,说明解决问题。

这是列约束语法与REFERENCES ....开始,是列定义的一部分(即列名是隐含的),而table_constraint语法与FORIEGN KEY(column_name) REFERENCES ...开始,遵循列定义

所以你可以有两种: -

Column_constraint语法

  • 作为列定义

  • category INTEGER NOT NULL REFERENCES categories (id)

例如的一部分

CREATE TABLE yourtablename (id INTEGER primary key autoincrement NOT NULL, name TEXT, description TEXT, expValue INTEGER, category INTEGER NOT NULL REFERENCES categories (id), date TEXT) 

Table_constraint语法

  • 列的后已被定义,但仍列定义即内仍然括号内。

  • FOREIGN KEY (category) REFERENCES categories (id)

即摹

CREATE TABLE yourtablename (id INTEGER primary key autoincrement NOT NULL, name TEXT, description TEXT, expValue INTEGER, category INTEGER NOT NULL, date TEXT, FOREIGN KEY (category) REFERENCES categories (id)); 

您可能会发现column-constraint和使用table-constraint


日期可以是列名。不过,我建议不要使用任何SQLite关键字(如date)作为列名称。