我是android编程和SQLite的新手,遇到了障碍。我有3张桌子; teams
,leagues
和一个名为teams_vs_leagues
的查找表,其中包含团队的ID和联盟的ID,以便它们相互关联。以下是表格设计:
//Create teams Table
private static final String CREATE_TEAMS_TABLE = "CREATE TABLE "
+ TEAMS_TABLE + "("
+ ID + " INTEGER PRIMARY KEY,"
+ TEAM_NAME + " TEXT,"
+ IMAGE + " TEXT" + ")";
//Create leagues Table
private static final String CREATE_LEAGUES_TABLE = "CREATE TABLE "
+ LEAGUES_TABLE + "("
+ ID + " INTEGER PRIMARY KEY,"
+ LEAGUE_NAME + " TEXT" + ")";
//Create teams_vs_leagues Table
private static final String CREATE_TEAMS_VS_LEAGUES_TABLE = "CREATE TABLE "
+ TEAMS_VS_LEAGUES_TABLE + "("
+ ID + " INTEGER PRIMARY KEY,"
+ TEAM_ID + " INTEGER,"
+ LEAGUE_ID + " INTEGER,"
+ POINTS + " INTEGER"+ ")";
以下是我添加新团队的方法:
public boolean createTeam(String team_name, String image, String team_id, String league_id, String points) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TEAM_NAME, team_name);
values.put(IMAGE, image);
long result = db.insert(TEAMS_TABLE, null, values);
if (result == -1)
return false;
else
return true;
}
如何将TEAM_ID
作为上面插入内容的ID添加到teams_vs_league
表中?任何帮助都将非常感激。
答案 0 :(得分:1)
根据SQLite API Android SQLite API,insert方法返回新插入行的行ID,如果发生错误则返回-1。
因此,您可以按如下方式更改代码:
long result = db.insert(TEAMS_TABLE, null, values);
if (result == -1) {
//throw error here
return false;
} else {
//result contains the id needed
//do something
return true;
}
干杯!快乐编程!
答案 1 :(得分:0)
insert()
方法返回新插入行的行ID,如果发生错误则返回-1。
所以你可以修改你的代码:
if (result == -1)
return false;
else
//create the record in the teams_vs_leagues here
//using result as TEAM_ID and league_id as LEAGUE_ID
return true;
}