数据库
首页 > 数据库> > Android SQLite外键语法错误

Android SQLite外键语法错误

作者:互联网

我刚刚开始在Android应用程序中使用SQLite数据库.我正在尝试制作“团队”表和“玩家”表,并且我希望“玩家”表具有外键,该外键引用“团队”表的自动递增_ID字段(我认为此_ID字段来自在我的合同类中实现BaseColumns).我以为语法正确,但出现以下错误(即使在卸载并重新安装我的应用程序之后)

06-08 20:26:22.763: E/Database(29843): Failure 1 (near "playerName": syntax error) on 0x22a110 when preparing 'CREATE TABLE player (_id INTEGER PRIMARY KEY,team_ID INTEGER, FOREIGN KEY(team_ID) REFERENCES team(_id), playerName TEXT,playerAge INTEGER,playerPosition TEXT,playerHeight REAL,playerWeight REAL,playerPhoto TEXT,playerNumber INTEGER)'.

上面的错误显示了最终试图通过的SQL语句.这是用于生成SQL语句的代码(很抱歉,它不必要地冗长,我正在阅读教程):

private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
        + TeamTable.TABLE_NAME + " (" + TeamTable._ID
        + " INTEGER PRIMARY KEY," + TeamTable.COLUMN_NAME_TEAM_NAME
        + TEXT_TYPE + COMMA_SEP + TeamTable.COLUMN_NAME_TEAM_WINS
        + TEXT_TYPE + COMMA_SEP + TeamTable.COLUMN_NAME_TEAM_LOSSES
        + TEXT_TYPE + COMMA_SEP + TeamTable.COLUMN_NAME_TEAM_LOGO
        + TEXT_TYPE + " )";

private static final String SQL_CREATE_ENTRIES_2 = "CREATE TABLE "
        + PlayerTable.TABLE_NAME + " (" + PlayerTable._ID
        + " INTEGER PRIMARY KEY," + "team_ID INTEGER, "
        + "FOREIGN KEY(team_ID) REFERENCES team(_id), "
        + PlayerTable.COLUMN_NAME_PLAYER_NAME + TEXT_TYPE + COMMA_SEP
        + PlayerTable.COLUMN_NAME_PLAYER_AGE + " INTEGER" + COMMA_SEP
        + PlayerTable.COLUMN_NAME_PLAYER_POSITION + TEXT_TYPE + COMMA_SEP
        + PlayerTable.COLUMN_NAME_PLAYER_HEIGHT + " REAL" + COMMA_SEP
        + PlayerTable.COLUMN_NAME_PLAYER_WEIGHT + " REAL" + COMMA_SEP
        + PlayerTable.COLUMN_NAME_PLAYER_PHOTO + TEXT_TYPE + COMMA_SEP
        + PlayerTable.COLUMN_NAME_PLAYER_NUMBER + " INTEGER" + ")";

然后,我使用execSQL(SQL_CREATE_ENTRIES)和execSQL(SQL_CREATE_ENTRIES_2,并且出现错误.我尝试仅创建“团队”表,而且看起来还可以,我什至可以从“团队”表中读取一些数据,在TextView中显示该值,但是当引入“ player”表时,事情就停止了工作,我可能会丢失一些非常明显的东西,但我似乎找不到它.

任何帮助是极大的赞赏!

解决方法:

首先声明所有列,然后在最后一列之后放置FOREIGN KEY(team_ID)REFERENCES team(_id).

所以最终的查询就像

CREATE TABLE player
(_id INTEGER PRIMARY KEY,
team_ID INTEGER, 
playerName TEXT,
playerAge INTEGER,
playerPosition TEXT,
playerHeight REAL,
playerWeight REAL,
playerPhoto TEXT,
playerNumber INTEGER,
FOREIGN KEY(team_ID) REFERENCES team(_id));

标签:sqlite,foreign-keys,syntax-error,android,database
来源: https://codeday.me/bug/20191030/1970660.html