CREATE_TASK TABLE String存在一些语法问题

时间:2014-06-27 13:56:05

标签: android database sqlite foreign-keys

此代码来自我的DatabaseHelper类 //这是两个表

private static final String TABLE_TASKS = "tasks";
private static final String TABLE_TASK_LIST = "task_list";

//这些是表列名称

private static final String KEY_PK = "_id";
private static final String KEY_TITLE = "title";
private static final String KEY_DETAILS = "details";
private static final String KEY_NOTES = "notes";
private static final String KEY_FK_TASKLIST_ID = "fk_tasklist_id";

//这些是将分配给db.exeSQL的字符串

private static final String CREATE_TASKS_TABLE = "CREATE TABLE "
+ TABLE_TASKS 
+ "(" 
+ KEY_PK
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TITLE + " TEXT,"
+ KEY_DETAILS + " TEXT," + KEY_NOTES + " TEXT," 
+ " FOREIGN KEY ("+ KEY_FK_TASKLIST_ID + ")" 
+ "REFERENCES " 
+ TABLE_TASK_LIST + "("+ KEY_PK + ")" 
+ ")";
private static final String CREATE_TASK_LIST_TABLE = "CREATE TABLE "
+ TABLE_TASK_LIST + "(" + KEY_PK
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_TITLE + " TEXT" +    ")";
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TASKS_TABLE);// create task table
} catch (Exception e) {
Log.e("onCreate Error", "TASKS_TABLE not created");
}
try {
db.execSQL(CREATE_TASK_LIST_TABLE);// create task list table
} catch (Exception e) {
Log.e("onCreate Error", "TASK_LIST_TABLE not created");
}
}

当我尝试插入数据时,字符串导致问题,表示表任务没有名为fk_tasklist_id的列

1 个答案:

答案 0 :(得分:0)

CREATE TABLE tasks (
    _id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    details TEXT,
    notes TEXT,
    FOREIGN KEY (fk_tasklist_id) REFERENCES task_list(_id)
)

在此表定义中,确实没有名为fk_tasklist_id的列。

要定义此类列,请将其添加到列列表中:

CREATE TABLE tasks (
    _id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    details TEXT,
    notes TEXT,
    fk_tasklist_id INTEGER,
    FOREIGN KEY (fk_tasklist_id) REFERENCES task_list(_id)
)

或者,将FK约束放在此列上:

CREATE TABLE tasks (
    _id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT,
    details TEXT,
    notes TEXT,
    fk_tasklist_id INTEGER REFERENCES task_list(_id)
)