Android sqlite邻接模型

时间:2014-08-28 12:56:26

标签: java android sql sqlite android-studio

我是Android开发的新手,在一个需要数据库交互的项目中工作 当尝试使用sqlite中的邻接模型创建表但编译失败时出现此错误消息

 |   id  |   parentid    |   name    |
-----------------------------------------
|   1    |   null        |   animal   |
|   2    |   null        |vegetable   |
|   3    |   1           |   doggie   |
|   4    |   2           |   carrot   |
|        |               |            |
|        |               |            |

这是我的代码:

private static final String CREATE_TABLE_CATEGORIES="CREATE TABLE "+TABLE_CATEGORIES+"(id INTEGER PRIMARY KEY AUTOINCREMENT,"+category_name+
            " TEXT,parentid INTEGER ,foreign key parentid_fk(parentid) references "+TABLE_CATEGORIES+" (id));";

@Override
    public void onCreate(SQLiteDatabase db){
        //Creation required tables


        db.execSQL(CREATE_TABLE_CATEGORIES);

    }
....
....
....
....
 @Override
    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
        // on upgrade drop older tables
        db.execSQL("PRAGMA foreign_keys = ON;");
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CATEGORIES);
        // create new tables
        onCreate(db);
    }

这是错误:

at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.database.sqlite.SQLiteException: near "parentid_fk": syntax error (code 1): , while compiling: CREATE TABLE Categories(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,parentid INTEGER ,foreign key parentid_fk(parentid) references Categories (id));

1 个答案:

答案 0 :(得分:2)

要为外键约束指定名称,必须使用CONSTRAINT关键字:

CONSTRAINT parentid_fk FOREIGN KEY (parentid) REFERENCES Categories(id)

或者,不要给它起个名字:

FOREIGN KEY (parentid) REFERENCES Categories(id)