我想对两个表使用外键,现在我的代码如下所示我得到语法错误。请解决此错误。提前致谢
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+ DB_TABLE+" ("+
KEY_TBNAME + " TEXT PRIMARY KEY NOT NULL);"
);
db.execSQL("CREATE TABLE " + DB_TABLE_CATE + " (" +
KEY_DETAIL + " TEXT NOT NULL, " +
KEY_AMOUNT + " INTEGER NOT NULL, " +
KEY_RESOURCE + " TEXT NOT NULL, " +
KEY_DATE + " TEXT NOT NULL, "+
KEY_TIME + " TEXT NOT NULL, " +
"FOREIGN KEY ("+KEY_TB_CATE+") REFERENCES "+DB_TABLE+" ("+KEY_TBNAME+");");
}
...错误
java.lang.RuntimeException:无法启动活动ComponentInfo {app.burhani.quickaccount / app.burhani.quickaccount.HomeActivity}:android.database.sqlite.SQLiteException:near“;”:语法错误(代码1): ,同时编译:CREATE TABLE tablenamecate(detail TEXT NOT NULL,amount INTEGER NOT NULL,resource TEXT NOT NULL,date TEXT NOT NULL,time TEXT NOT NULL,FOREIGN KEY(tbnameis)REFERENCES tablename(tbname);
答案 0 :(得分:1)
这将是真正的查询:
CREATE TABLE DB_TABLE ( KEY_TBNAME TEXT PRIMARY KEY NOT NULL)
CREATE TABLE DB_TABLE_CATE (
KEY_DETAIL TEXT NOT NULL,
KEY_AMOUNT INTEGER NOT NULL,
KEY_RESOURCE TEXT NOT NULL,
KEY_DATE TEXT NOT NULL,
KEY_TIME TEXT NOT NULL,
KEY_TBNAME TEXT NOT NULL,
FOREIGN KEY(KEY_TBNAME) REFERENCES DB_TABLE(KEY_TBNAME));
您必须定义KEY_TBNAME然后设置外键。 我可以在sqlite浏览器中运行此查询,它对我有用
答案 1 :(得分:1)
您得到near ";": syntax error
,因为您需要两个右括号,一个用于FK列名称列表,另一个用于表列列表:
... REFERENCES DB_TABLE(KEY_TBNAME));
您还有另一个错误:FK中的列KEY_TB_CATE必须也出现在列列表中。