sqlite3在android中创建表错误

时间:2015-08-14 20:09:01

标签: android sqlite

我正在尝试使用sqlite3在android中创建表 我的开放助手就是:

public class TaskOpenHelper extends BaseOpenHelper {
    public static final String TABLE_NAME = "tasks";
    public static final String COL_ID = "id";
    public static final String COL_USER_ID = "user_id";
    public static final String COL_TITLE = "title";
    public static final String COL_DATE = "date";
    public static final String COL_TIME = "time";
    public static final String COL_IS_DONE = "is_done";
    public static final String COL_IS_IPM = "is_ipm";
    public static final String COL_DESC = "desc";
    public static final String COL_REGISTER_TIME = "register_time";
    public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
            "(" +
            COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            COL_USER_ID + " INTEGER NOT NULL," +
            COL_TITLE + " TEXT NOT NULL," +
            COL_DATE + " TEXT ," +
            COL_TIME + " TEXT ," +
            COL_IS_DONE + " INTEGER ," +
            COL_IS_IPM + " INTEGER ," +
            COL_DESC + " TEXT," +
            COL_REGISTER_TIME + " TEXT," +
            "FOREIGN KEY " + COL_USER_ID + " REFERENCES " + UserOpenHelper.TABLE_NAME + "(" + UserOpenHelper.COL_ID + ")" +
            ");";


    public TaskOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        sqLiteDatabase.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(sqLiteDatabase);
    }

但是当我在尝试创建表时运行app时,这个错误得到了确认:

Caused by: android.database.sqlite.SQLiteException: near "user_id": syntax error (code 1): , while compiling: CREATE TABLE IF NOT EXISTS tasks(id INTEGER PRIMARY KEY AUTOINCREMENT,user_id INTEGER NOT NULL,title TEXT NOT NULL,date TEXT ,time TEXT ,is_done INTEGER ,is_ipm INTEGER ,desc TEXT,register_time TEXT,FOREIGN KEY user_id REFERENCES user(Id));

这个open helper在数据源类中用于执行db

中的查询

1 个答案:

答案 0 :(得分:2)

您需要在user_id子句的括号中加上FOREIGN KEY

FOREIGN KEY (user_id) REFERENCES user(Id)

整个陈述应该看起来像

CREATE TABLE IF NOT EXISTS tasks(id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    title TEXT NOT NULL,
    date TEXT,
    time TEXT,
    is_done INTEGER,
    is_ipm INTEGER,
    desc TEXT,
    register_time TEXT,
    FOREIGN KEY user_id REFERENCES user(Id));

此外,您必须更改desc列的名称,因为这是SQLite中的reserved word