3

我刚刚开始在 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)and execSQL(SQL_CREATE_ENTRIES_2,出现错误。我尝试只创建“团队”表,它似乎工作正常。我什至可以从“团队”表中读取一些数据并在 TextView 中显示该值。但是当“玩家”表被引入时,事情就停止了。我可能遗漏了一些非常明显的东西,但我似乎找不到它。

任何帮助是极大的赞赏!

4

1 回答 1

5

首先声明所有列,然后将其放在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));
于 2013-06-09T01:12:01.997 回答