Android中的SQLite:外键和预期

时间:2017-11-10 21:26:17

标签: java android mysql 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');");
}

错误发生在' date TEXT',错误显示:

<table constraint> expected, got 'date'.

这里的问题是什么?

1 个答案:

答案 0 :(得分:3)

您的问题是,您已将 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语法以 {{开头1}}并遵循列定义

所以你可以: -

Column_constraint语法

  • 作为列定义的一部分

  • FORIEGN KEY(column_name) REFERENCES ...

e.g。

category INTEGER NOT NULL REFERENCES categories (id)

Table_constraint语法

    列之后
  • ,但仍在列定义内,即仍在括号内。

  • 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)

e.g

FOREIGN KEY (category) REFERENCES categories (id)

您可能会发现使用column-constrainttable-constraint

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