我刚刚开始在Android应用中使用SQLite数据库。我正在尝试创建一个'团队'表和一个'播放器'表,我希望'player'表有一个外键,它引用'team'表的自动增量_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
,然后出现错误。我试过只创建'团队'表,它似乎工作正常。我甚至能够从'team'表中读取一些数据并在TextView中显示该值。但是当“玩家”表被引入时,事情就会停止工作。我可能错过了一些非常明显的东西,但我似乎无法找到它。
非常感谢任何帮助!
答案 0 :(得分:4)
首先声明所有列,然后将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));