gpt4 book ai didi

java - Android sqlite邻接模型

转载 作者:行者123 更新时间:2023-12-02 05:30:52 25 4
gpt4 key购买 nike

我是 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));

最佳答案

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

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

或者,不要给它命名:

FOREIGN KEY (parentid) REFERENCES Categories(id)

关于java - Android sqlite邻接模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com